-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathcreateResolvers.js
69 lines (63 loc) · 2.77 KB
/
createResolvers.js
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
const fs = require('fs');
const beautify = require('js-beautify').js;
const { uppercase } = require('../utils');
module.exports = ({ destination, flavor, name }) => {
const modelFolder = `${destination}/graphql`;
const indexFile = `${modelFolder}/resolvers.js`;
const code = `
const ${uppercase(name)} = require('../models/${name}');
const prepare = require('./prepare');
const { ObjectId } = require('mongodb');
module.exports = {
Query: {
${name}: async (root, {_id}) => {
// // @TODO Permissions,
// if (!permission) throw new Error('Permission denied for userCan getOne ${name}');,
return await ${uppercase(name)}.findOne({ _id });
},
${name}s: async () => {
// // @TODO Permissions,
// const permission = userCan('get', '${name}', req.user, args);,
// if (!permission) throw new Error('Permission denied for userCan get ${name}');,
return await ${uppercase(name)}.find({});
},
},
Mutation: {
create${uppercase(name)}: async (root, args, context, info) => {
// // @TODO Permissions,
// const permission = userCan('create', '${name}', req.user, args);,
// if (!permission) throw new Error('Permission denied for userCan create ${name}');,
const new${uppercase(name)} = await ${uppercase(name)}.create(args);
return new${uppercase(name)};
},
update${uppercase(name)}: async (root, args, context, info) => {
const argscopy = Object.assign({}, args);
delete argscopy._id;
let getOne = await ${uppercase(name)}.findOne({ _id: args._id });
Object.keys(args).forEach(key => getOne[key] = args[key]);
// // @TODO Permissions,
// const permission = userCan('update', '${name}', req.user, args);,
// if (!permission) throw new Error('Permission denied for userCan update ${name}');,
await getOne.save();
return getOne;
},
delete${uppercase(name)}: async (root, args, context, info) => {
const getOne = await ${uppercase(name)}.findOne({ _id: args._id });
// // @TODO Permissions,
// const permission = userCan('delete', '${name}', req.user, args);,
// if (!permission) throw new Error('Permission denied for userCan delete ${name}');,
if (!getOne) throw new Error('not found')
await getOne.delete();
return getOne;
},
},
};
`;
// if (logging) console.log('checking user-can');
if (!fs.existsSync(modelFolder)) {
// if (logging) console.log('creating user-can');
fs.mkdirSync(modelFolder);
}
const pretty = beautify(code, { indent_size: 2, space_in_empty_paren: true });
fs.writeFileSync(indexFile, pretty);
};