1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | 2× 2× 2× 2× 2× 2× 2× 2× 65× 1× 64× 1× 63× 61× 61× 61× 11× 11× 61× 61× 1× 9× 9× 1× 8× 8× 8× 8× 8× 7× 8× 3× 8× 1× 8× 7× 1× 1× 1× 1× 7× 1× 6× 6× 1× 5× 5× 5× 5× 5× 4× 4× 1× 6× 6× 6× 1× 5× 1× 4× 4× 4× 4× 4× 3× 3× 3× 1× 3× 3× 1× 2× 3× 3× 1× 2× 2× 2× 9× 9× 9× 9× 9× 9× 3× 9× 8× 8× 1× 5× 5× 1× 4× 4× 4× 4× 3× 2× 1× 1× 4× 4× 1× 3× 3× 3× 2× 1× 2× 2× 3× 1× 2× 2× 2× 65× 61× 61× 1× 61× 61× 61× 61× 61× 427× 427× 65× 362× 362× 362× 362× 362× 362× 362× 362× 362× 364× 60× 102× 364× 364× 362× 362× 364× 364× 1× 427× 61× 366× 1× 362× 362× 120× 242× 362× 362× 1× 362× 120× 242× 1× 362× 60× 60× 60× 62× 120× 1× 463× 1× 33× 25× 8× 8× 8× 13× 13× 1× 12× 8× 1× 113× 113× 113× 113× 2× 2× 1× 2× | 'use strict'; const is = require('is'); const bodyParser = require('body-parser'); const extend = require('extend'); const errorsHandler = require('./errorsHandler'); const arrify = require('arrify'); const S = require('string'); const pluralize = require('pluralize'); const OPERATIONS = ['list', 'get', 'create', 'updatePatch', 'updateReplace', 'delete', 'deleteAll']; class ApiBuilder { constructor(Model, settings) { if (!Model) { throw new Error('Model missing'); } if (settings && {}.hasOwnProperty.call(settings, 'path') && !is.string(settings.path)) { throw new Error('Path must be a string'); } const modelSettings = { readAll: Model.schema.options.queries.readAll, showKey: Model.schema.options.queries.showKey, }; this.Model = Model; this.settings = extend(true, {}, this.constructor.defaultSettings, modelSettings, this.constructor.overrides, settings); /** * If no path passed, auto generate path from Entity Kind * It automatically pluralize the path * ex : Entity Kind 'BlogPost' ---> path = 'blog-posts' */ if (!{}.hasOwnProperty.call(this.settings, 'path')) { const path = pathFromEntityKind(this.Model.entityKind); this.settings.path = `/${path}`; } createRoutes(this); return this; } /** * Add override settings that take over the default settings * and the Model "queries" settings (for showKey and readAll) { readAll: true | false, showKey: true | false, contexts : { // (optional) public : '', private : '/private', } } */ static setOverrides(settings) { this.overrides = Object.assign({}, settings); } list(req, res) { const opConfig = operationConfig(this.settings, 'list'); // If a function is passed for "list" execute it if (opConfig.handler) { return opConfig.handler(req, res); } const _this = this; const options = opConfig.options || {}; const ancestors = ancestorsFromParams(req.params, this.settings.ancestors); const settings = extend(true, {}, options); if (!{}.hasOwnProperty.call(settings, 'showKey')) { settings.showKey = this.settings.showKey; } if (ancestors) { settings.ancestors = ancestors; } if (req.query.pageCursor) { settings.start = req.query.pageCursor; } return this.Model.list(settings) .then((response) => { if (response.nextPageCursor) { /** * Add Link Header to response */ let uri = _this.settings.host || `${req.protocol}://${req.get('host')}`; req.originalUrl = req.originalUrl.replace(/\?pageCursor=[^&]+/, ''); uri += `${req.originalUrl}?pageCursor=${response.nextPageCursor}`; res.set('Link', `<${uri}>; rel="next"`); } return res.json(response.entities); }) .catch(err => errorsHandler.rpcError(err, res)); } get(req, res) { const opConfig = operationConfig(this.settings, 'get'); if (opConfig.handler) { return opConfig.handler(req, res); } const _this = this; const options = opConfig.options || {}; const ancestors = ancestorsFromParams(req.params, this.settings.ancestors); const args = ancestors ? [req.params.id, ancestors] : [req.params.id]; return this.Model.get.apply(this.Model, args) .then((entity) => { const plainOptions = { readAll: typeof options.readAll === 'undefined' ? _this.settings.readAll : options.readAll, showKey: typeof options.showKey === 'undefined' ? _this.settings.showKey : options.showKey, }; return res.json(entity.plain(plainOptions)); }) .catch(err => errorsHandler.rpcError(err, res)); } create(req, res) { const _this = this; const opConfig = operationConfig(this.settings, 'create'); if (opConfig.handler) { return opConfig.handler(req, res); } if (req.file) { return res.status(500).send('File upload must be handle in custom handlers'); } const data = this.Model.sanitize(req.body); const ancestors = ancestorsFromParams(req.params, this.settings.ancestors); const model = ancestors ? new this.Model(data, null, ancestors) : new this.Model(data); const options = opConfig.options || {}; return model.save() .then((entity) => { const plainOptions = { readAll: typeof options.readAll === 'undefined' ? _this.settings.readAll : options.readAll, showKey: typeof options.showKey === 'undefined' ? _this.settings.showKey : options.showKey, }; res.location(`${req.path}/${entity.plain(plainOptions).id}`); return res.status(201).json(entity.plain(plainOptions)); }) .catch(err => errorsHandler.rpcError(err, res)); } updatePatch(req, res) { const opConfig = operationConfig(this.settings, 'updatePatch'); if (opConfig.handler) { return opConfig.handler(req, res); } return this.update(req, res, opConfig.options); } updateReplace(req, res) { const opConfig = operationConfig(this.settings, 'updateReplace'); if (opConfig.handler) { return opConfig.handler(req, res); } const options = opConfig.options || {}; options.replace = true; return this.update(req, res, options); } update(req, res, options) { options = typeof options === 'undefined' ? {} : options; const _this = this; const data = this.Model.sanitize(req.body); const ancestors = ancestorsFromParams(req.params, this.settings.ancestors); let args = ancestors ? [req.params.id, data, ancestors] : [req.params.id, data, null]; if (options.replace === true) { args = args.concat([null, null, { replace: true }]); } return this.Model.update.apply(this.Model, args) .then((entity) => { const plainOptions = { readAll: typeof options.readAll === 'undefined' ? _this.settings.readAll : options.readAll, showKey: typeof options.showKey === 'undefined' ? _this.settings.showKey : options.showKey, }; return res.json(entity.plain(plainOptions)); }) .catch(err => errorsHandler.rpcError(err, res)); } _delete(req, res) { const opConfig = operationConfig(this.settings, 'delete'); if (opConfig.handler) { return opConfig.handler(req, res); } const _this = this; const ancestors = ancestorsFromParams(req.params, this.settings.ancestors); const args = ancestors ? [req.params.id, ancestors] : [req.params.id]; return this.Model.delete.apply(this.Model, args) .then((response) => { if (response.success) { return res.json({ success: true, message: `${_this.Model.entityKind} "${req.params.id}" deleted successfully.`, }); } return res.json({ success: false, message: `Could not delete entity. ${_this.Model.entityKind} "${req.params.id}" not found`, }); }) .catch(err => errorsHandler.rpcError(err, res)); } deleteAll(req, res) { const opConfig = operationConfig(this.settings, 'deleteAll'); if (opConfig.handler) { return opConfig.handler(req, res); } const ancestors = ancestorsFromParams(req.params, this.settings.ancestors); const args = ancestors ? [ancestors] : []; return this.Model.deleteAll.apply(this.Model, args) .then(response => res.json(response)) .catch(err => errorsHandler.rpcError(err, res)); } } ApiBuilder.defaultSettings = { contexts: { public: '', private: '', }, readAll: false, showKey: false, }; /** * ApiBuilder create * @param {*} Model -- gstore-node Model * @param {*} settings -- configuration settings * * settings is an object with the following parameters { path:'/users', -- (optional) the path for the resource. If not passed will be autogenerated showKey: true | false -- (default false) readAll: true | false (default false) operations: { list: { ... }, get: { ... }, create: { ... }, update: { ... }, delete: { ... }, deleteAll: { ... } } } */ // const create = (Model, settings) => new ApiBuilder(Model, settings); /** * Express Api builder * * @param {Router} router -- Express Router */ const express = (router) => { if (!router) { throw new Error('Router missing or wrong type.'); } ApiBuilder.engine = 'express'; ApiBuilder.router = router; return { create: (Model, settings) => { const api = new ApiBuilder(Model, settings); router.__gstoreApi = api; return router; }, }; }; /** * Function that loops through each of the operation and creates a route for it * Each operation can be customized in the settings with an object: * { exec: true, // default "true"" except for "deleteAll"" wich defaults to false middleware: someMiddlewareMethod, handler: someControllerMethod, path : { prefix: 'some-prefix', suffix: 'some-suffix', }, } */ function createRoutes(self) { const settings = self.settings; const pathWithId = ['get', 'updatePatch', 'updateReplace', 'delete']; const verbWithBody = ['create', 'updatePatch', 'updateReplace']; const router = self.constructor.router; OPERATIONS.forEach((operation) => { const config = operationConfig(settings, operation); if (!executeOperation(operation, config)) { return; } const prefixes = getPrefixes(operation, config); const suffix = config && config.path && config.path.suffix ? config.path.suffix : ''; const ancestors = {}.hasOwnProperty.call(settings, 'ancestors') ? arrify(settings.ancestors) : undefined; const paths = []; const verb = operationToVerb(operation); const method = operation === 'delete' ? '_delete' : operation; let middleware = verbWithBody.indexOf(method) >= 0 ? [bodyParser.json()] : []; middleware = config.middleware ? middleware.concat(arrify(config.middleware)) : middleware; prefixes.forEach((prefix) => { if (ancestors) { ancestors.forEach((ancestor, index) => { prefix += `/${pathFromEntityKind(ancestor)}/:anc${index}ID`; }); } const path = pathWithId.indexOf(operation) < 0 ? prefix + settings.path + suffix : `${prefix + settings.path}/:id${suffix}`; paths.push(path); }); const args = middleware.concat([self[method].bind(self)]); paths.forEach((path) => { const route = router.route(path); route[verb].apply(route, args); }); }); /** * Check if the operation is active and should be executed (route created) * @param {*} operation -- the operation * @param {object} operationConfig -- config of the operation * @returns {boolean} -- active or not */ function executeOperation(operation, operationConfig) { // For security reason deleteAll must be explicitly set to true if (operation === 'deleteAll') { return !!operationConfig.exec; } return operationConfig.exec !== false; } /** * Returns prefix(es) of the route for an operation * Plural because we can define several prefixes for a same Model Action * and thus several routes are created * @param {string} operation -- the operation * @param {object} config -- config of the operation * @returns {Array} -- the prefixes */ function getPrefixes(operation, config) { let prefix = ''; if (isPublic(operation)) { prefix = settings.contexts.public; } else { prefix = settings.contexts.private; } prefix = config && config.path && config.path.prefix ? config.path.prefix : prefix; return arrify(prefix); } function isPublic(operation) { switch (operation) { case 'list': case 'get': return true; default: return false; } } function operationToVerb(operation) { switch (operation) { case 'create': return 'post'; case 'updatePatch': return 'patch'; case 'updateReplace': return 'put'; case 'delete': case 'deleteAll': return 'delete'; default: return 'get'; } } } function operationConfig(config, operation) { return config.operations && {}.hasOwnProperty.call(config.operations, operation) ? config.operations[operation] : {}; } /** * Build Ancestors Array from request params and ancestors setting * Ex: for a route /blog/nameblog/blogpost/123 and ancestor setting 'Blog' * ---> returns array ['Blog', 'nameblog'] */ function ancestorsFromParams(params, ancestors) { if (!ancestors) { return null; } let arr = []; ancestors = arrify(ancestors); ancestors.forEach((ancestor, index) => { const id = `anc${index}ID`; if (!params[id]) { return; } arr = arr.concat([ancestor, params[id]]); }); return arr; } function pathFromEntityKind(entityKind) { let path = entityKind.substr(0, 1).toLowerCase() + entityKind.substr(1); path = S(path).dasherize().s; path = pluralize(path, 2); return path; } module.exports = (settings) => { if (settings) { ApiBuilder.setOverrides(settings); } return { express, }; }; |