Merge pull request #103 from keen-studio/globals-separate-routes

globals with paths for subdocs supported
This commit is contained in:
Dan Ribbens
2019-10-17 14:48:58 -04:00
committed by GitHub
3 changed files with 31 additions and 5 deletions

View File

@@ -192,10 +192,16 @@ class Payload {
);
}
options.router.all('/globals',
options.router.all('/globals*',
bindModelMiddleware(globalModel),
setModelLocaleMiddleware()
).route('/globals')
);
options.router
.route('/globals')
.get(fetch);
options.router.route('/globals/:key')
.get(fetch)
.post(upsert)
.put(upsert);

View File

@@ -11,7 +11,15 @@ const fetch = (req, res) => {
};
findOne(query, createAutopopulateOptions(query))
.then(doc => res.json(doc))
.then(doc => {
if (doc[req.params.key]) {
return res.json(doc[req.params.key]);
} else if (req.params.key) {
return res.status(httpStatus.NOT_FOUND)
.json({error:'not found'});
}
return res.json(doc);
})
.catch(err => res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ error: err }));
};

View File

@@ -2,8 +2,14 @@ import httpStatus from 'http-status';
const upsert = (req, res) => {
req.model.findOne({}, (err, doc) => {
let global = {};
if (!doc) {
req.model.create(req.body, (err, result) => {
if (req.params.key) {
global[req.params.key] = req.body;
} else {
global = req.body;
}
req.model.create(global, (err, result) => {
if (err)
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({error: err});
@@ -14,8 +20,14 @@ const upsert = (req, res) => {
});
});
} else {
if (!req.model.schema.paths[req.params.key]) {
return res.status(httpStatus.NOT_FOUND).json({error: 'not found'});
}
if (!doc[req.params.key]) {
doc[req.params.key] = {};
}
Object.keys(req.body).forEach(e => {
doc[e] = req.body[e];
doc[req.params.key][e] = req.body[e];
});
doc.save((err) => {
if (err)