UNPKG

built.io

Version:

SDK for Built.io Backend

75 lines (70 loc) 2.51 kB
var R = require('ramda'); var utility = require('./utilities/utility'); var instanceMethodBuilder = require('./utilities/instanceMethodBuilder')(); /** * @class Upsert * @classdesc * Built.Upsert is a helper module for performing upsert operations on group fields(fields inside a group field). * @instance * @description Instances created using Built.Upsert can placed against a field uid on which upsert operations are to be performed. * @param {JSONObject| Array } data Single or Array of plain JavaScript object(s). Each object should contain a 'condition' key specifying the upsert condition(s) and * a 'replacement' key specifying the upsert(s). * @example * //'blt5d4sample2633b' is a dummy Application API key * // Class('class_name').Object returns a Object constructor * // 'project' is a uid of a class on Built.io Backend * // 'person' is a reference field in 'employee' group. * // If a person with name 'John' and age 24 is to be searched * // If such a person is found rename him to 'Jack' with proffession set to 'developer' else * // create a new object with these details * var upsertOp = Built.Upsert([{ * condition: { * name: 'John', * age: 24 * }, * replacement: { * name: 'Jack', * age: 24, * proffession: 'developer' * } * }]); * var employee = Built.Group('team', { * employees: upsertOp, * emp_id: 'emp123' * }) * var app = Built.App('blt5d4sample2633b'); * var project = app.Class('project').Object(); * project = project.addGroup(employee) * project.save() * .then(function(project) { * console.log(project.toJSON()) * }) * @return {Upsert} */ var upsertCons = module.exports = function(conditionStructure) { var data = conditionStructure // Iteratively converts from user friendly format to Backend's UPSERT format if(utility.isArray(conditionStructure)) data = iterativelyConstructUpsertStructure(conditionStructure) else data = constructUpsertStructure(conditionStructure) var returnObj = { data : data, _isUpsert : true, toJSON : function() { return this.data } } return instanceMethodBuilder.build(module.exports, returnObj) } function iterativelyConstructUpsertStructure(upsertStructures){ return upsertStructures.map(function(upsertStruct){ return constructUpsertStructure(upsertStruct) }) } function constructUpsertStructure(upsertStruct) { var upsertObj = { UPSERT: upsertStruct.condition } return R.mixin(upsertObj, upsertStruct.replacement) }