feat(associate): routes to associate objects with each other
This commit is contained in:
parent
e647922678
commit
5e0eeccbac
@ -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
|
||||
```
|
||||
|
@ -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"
|
||||
}
|
||||
}
|
||||
|
37
src/associations/associate.js
Normal file
37
src/associations/associate.js
Normal file
@ -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);
|
||||
}
|
||||
})
|
||||
}
|
@ -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 };
|
||||
|
@ -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.
|
||||
|
Loading…
Reference in New Issue
Block a user