Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update mongoose to latest v5 #813

Merged
merged 9 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/models/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"jsonpath": "^1.1.1",
"lodash.isequal": "^4.5.0",
"moment": "^2.29.4",
"mongoose": "^4.13.21",
"mongoose": "^5.13.20",
"mongoose-timestamp": "^0.6",
"pino": "^8.8.0",
"uuid": "^8.3.2"
Expand Down
186 changes: 102 additions & 84 deletions packages/models/src/box/box.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,95 +44,113 @@ const locationSchema = new Schema({
});

//senseBox schema
const boxSchema = new Schema({
name: {
type: String,
required: true,
trim: true
},
locations: {
type: [locationSchema],
required: true,
},
currentLocation: {
type: locationSchema,
required: true,
},
exposure: {
type: String,
trim: true,
required: true,
enum: ['unknown', 'indoor', 'outdoor', 'mobile']
},
grouptag: {
type: [String], // Default value for array is [] (empty array)
trim: true,
required: false
},
model: {
type: String,
required: true,
trim: true,
default: 'custom',
enum: ['custom', ...sensorLayouts.models]
},
weblink: {
type: String,
trim: true,
required: false
},
description: {
type: String,
trim: true,
required: false
},
image: {
type: String,
trim: true,
required: false,
/* eslint-disable func-name-matching */
set: function imageSetter ({ type, data, deleteImage }) {
/* eslint-enable func-name-matching */
if (type && data) {
const filename = `${this._id}_${Math.round(Date.now() / 1000).toString(36)}.${type}`;
try {
fs.writeFileSync(`${imageFolder}${filename}`, data);
} catch (err) {
log.warn(err);

return;
}
const boxSchema = new Schema(
{
name: {
type: String,
required: true,
trim: true
},
locations: {
type: [locationSchema],
required: true
},
currentLocation: {
type: locationSchema,
required: true
},
exposure: {
type: String,
trim: true,
required: true,
enum: ['unknown', 'indoor', 'outdoor', 'mobile']
},
grouptag: {
type: [String], // Default value for array is [] (empty array)
trim: true,
required: false
},
model: {
type: String,
required: true,
trim: true,
default: 'custom',
enum: ['custom', ...sensorLayouts.models]
},
weblink: {
type: String,
trim: true,
required: false
},
description: {
type: String,
trim: true,
required: false
},
image: {
type: String,
trim: true,
required: false,
/* eslint-disable func-name-matching */
set: function imageSetter ({ type, data, deleteImage }) {
/* eslint-enable func-name-matching */
if (type && data) {
const filename = `${this._id}_${Math.round(
Date.now() / 1000
).toString(36)}.${type}`;
try {
fs.writeFileSync(`${imageFolder}${filename}`, data);
} catch (err) {
log.warn(err);

return;
}

return filename;
} else if (deleteImage === true) {
if (this.image) {
const oldFilename = `${imageFolder}${this.image}`;
const extensionToUse = this.image.slice(this.image.lastIndexOf('.'));
const newFilename = `${imageFolder}${Buffer.from((Buffer.from(`${Math.random().toString(36)
.slice(2)}${Date.now()}`).toString('base64'))).toString('hex')}${extensionToUse}`;
fs.rename(oldFilename, newFilename, () => {});
return filename;
} else if (deleteImage === true) {
if (this.image) {
const oldFilename = `${imageFolder}${this.image}`;
const extensionToUse = this.image.slice(
this.image.lastIndexOf('.')
);
const newFilename = `${imageFolder}${Buffer.from(
Buffer.from(
`${Math.random().toString(36)
.slice(2)}${Date.now()}`
).toString('base64')
).toString('hex')}${extensionToUse}`;
fs.rename(oldFilename, newFilename, () => {});
}
}
}
},
sensors: {
type: [sensorSchema],
// required: [true, 'sensors are required if model is invalid or missing.'],
// https://github.com/Automattic/mongoose/issues/5139#issuecomment-429990002
validate: {
validator: (v) => {
return v === null || v.length > 0;
},
message: () => 'sensors are required if model is invalid or missing.'
}
},
lastMeasurementAt: {
type: Date,
required: false
},
access_token: {
type: String,
required: true
},
useAuth: {
type: Boolean,
required: true,
default: false
}
},
sensors: {
type: [sensorSchema],
required: [true, 'sensors are required if model is invalid or missing.'],
},
lastMeasurementAt: {
type: Date,
required: false
},
access_token: {
type: String,
required: true
},
useAuth: {
type: Boolean,
required: true,
default: false,
}
}, { usePushEach: true });
{ usePushEach: true }
);
boxSchema.plugin(timestamp);

const BOX_PROPS_FOR_POPULATION = {
Expand Down
2 changes: 1 addition & 1 deletion packages/models/src/box/integrations.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const integrationSchema = new mongoose.Schema({
validator: function validTTNDecodeOptions (ttn) {
/* eslint-enable func-name-matching */
if (['debug', 'lora-serialization', 'cayenne-lpp'].indexOf(ttn.profile) !== -1) {
return (ttn.decodeOptions && ttn.decodeOptions.constructor === Array);
return (ttn.decodeOptions && Array.isArray(ttn.decodeOptions));
}
},
msg: 'this profile requires an array \'decodeOptions\''
Expand Down
4 changes: 2 additions & 2 deletions packages/models/src/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ const connect = function connect (uri) {
return new Promise(function (resolve, reject) {
mongoose
.connect(uri, {
useMongoClient: true,
reconnectTries: Number.MAX_VALUE,
useNewUrlParser: true,
useUnifiedTopology: true,
promiseLibrary: global.Promise
})
.then(function () {
Expand Down
27 changes: 19 additions & 8 deletions packages/models/test/tests/0-user.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@ const shouldNotHappenThenner = function (err) {
expect(false).true;
};

const getDevices = function () {
const boxes = [
senseBox({ name: 'sb1' }),
senseBox({ name: 'sb2' }),
senseBox({ name: 'sb3' })
];

return new Promise((resolve) => {
setTimeout(() => resolve(boxes), 200);
});
};

describe('User model', function () {
before(function () {
return connect(dbConnectionString({ db: 'userTest' }))
Expand Down Expand Up @@ -506,15 +518,14 @@ describe('User model', function () {
});

describe('Box management', function () {
const boxes = [senseBox({ name: 'sb1' }), senseBox({ name: 'sb2' }), senseBox({ name: 'sb3' })];
let userBoxes;
before(function () {
return User.findOne({ name: 'Valid Username 2' })
.then(function (user) {
return Promise.all(boxes.map(function (box) {
return user.addBox(box);
}));
});
before(async function () {
const user = await User.findOne({ name: 'Valid Username 2' });

const devices = await getDevices();
for (const device of devices) {
await user.addBox(device);
}
});

it('should allow to get all boxes with all details of a user', function () {
Expand Down
Loading
Loading