diff --git a/README.md b/README.md index 19573f3..d48a7d3 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,9 @@ DELETE /role/{id}/teams?members=5 DELETE /team/{id}/role/{id} DELETE /role/{id}/team/{id} +# you also get routes to associate objects with each other +GET /associate/role/{id}/employee/{id} # associates role {id} with employee {id} + # you can specify a prefix to change the URLs like this: GET /v1/team/{id}/roles ``` diff --git a/package.json b/package.json index 9b21075..1e52d78 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hapi-sequelize-crud", - "version": "1.2.1", + "version": "1.3.0", "description": "Hapi plugin that automatically generates RESTful API for CRUD", "main": "build/index.js", "config": { @@ -28,6 +28,7 @@ "grunt-contrib-watch": "0.6.1" }, "dependencies": { - "joi": "7.2.1" + "joi": "7.2.1", + "lodash": "4.0.0" } } diff --git a/src/associations/associate.js b/src/associations/associate.js new file mode 100644 index 0000000..5c6772e --- /dev/null +++ b/src/associations/associate.js @@ -0,0 +1,37 @@ +import joi from 'joi'; +import error from '../error'; +import { capitalize } from 'lodash/string'; + +let prefix; + +export default (server, a, b, options) => { + prefix = options.prefix; + + console.log(`${prefix}/associate/${a._singular}/{aid}/${b._singular}/{bid}`); + server.route({ + method: 'GET', + path: `${prefix}/associate/${a._singular}/{aid}/${b._singular}/{bid}`, + + @error + async handler(request, reply) { + let instanceb = await b.findOne({ + where: { + id: request.params.bid + } + }); + + let instancea = await a.findOne({ + where: { + id: request.params.aid + } + }); + + let fna = (instancea['add' + b.name] || instancea['set' + b.name]).bind(instancea); + let fnb = (instanceb['add' + a.name] || instanceb['set' + a.name]).bind(instanceb); + await fna(instanceb); + await fnb(instancea); + + reply(instancea); + } + }) +} diff --git a/src/associations/index.js b/src/associations/index.js index 518ee27..164bce3 100644 --- a/src/associations/index.js +++ b/src/associations/index.js @@ -1,4 +1,5 @@ import oneToOne from './one-to-one'; import oneToMany from './one-to-many'; +import associate from './associate'; -export { oneToOne, oneToMany }; +export { oneToOne, oneToMany, associate }; diff --git a/src/index.js b/src/index.js index c168caa..7fd9b93 100644 --- a/src/index.js +++ b/src/index.js @@ -50,6 +50,9 @@ const register = (server, options = {}, next) => { associations.oneToMany(server, source, target, options); associations.oneToMany(server, target, source, options); } + + associations.associate(server, source, target, options); + associations.associate(server, target, source, options); } catch(e) { // There might be conflicts in case of models associated with themselves and some other // rare cases.