@axway/api-builder-plugin-dc-mbs
Version:
Mobile Backend Services connector
59 lines (54 loc) • 1.88 kB
JavaScript
const ignoreMissingFields = true; // readability
const MBSID = new RegExp(/[a-f0-9]{24}/i);
function upsert(Model, id, fields, next) {
this.logger.trace('MBS.upsert', { id, fields, model: Model.name });
// There is a question as to whether or not `id` is required. It is
// implemented inconsistently in various connectors. The closest,
// mongo, allows `id` to be falsey, and will perform an insert.
//
// Also, there is a question what to do when `id` is provided, but no
// record is found. Some connectors simply create a record with the
// `id`. In this case, the user intended for a record to exist, and
// supplied an `id`, so the result _should_ be an error. However, we
// wrote the integration tests to say otherwise, so if `id` is
// provided and it does not exist, create it.
if (id) {
if (!id.match(MBSID)) {
return next(new Error('Invalid id parameter; must be a 24 character hex string'));
}
this.findByID(Model, id, (err, record) => {
if (err) {
// no need to translate
next(err);
} else if (!record) {
// insert
this.create(Model, fields, next);
} else {
// update existing record
const pkName = Model.getPrimaryKeyName();
// Create an instance of the model (ignoring missing fields) so that
// we can do a translation of the field values. Otherwise, there is
// no direct way to do a reverse map.
const instance = Model.instance(fields, ignoreMissingFields);
for (const field in Model.fields) {
if (field === pkName) {
continue;
} else {
const value = instance[field];
if (value !== undefined) {
// Update the record instance with the updated value.
record[field] = value;
}
}
}
this.save(Model, record, next);
}
});
} else {
// insert
this.create(Model, fields, next);
}
}
module.exports = {
upsert
};