Created
May 5, 2020 15:51
-
-
Save Noitidart/65061c94d7f9320d418672cd24b83e52 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { routes } = require('../../../config/routes'); | |
const pluralize = require('pluralize'); | |
const { camelCase } = require('lodash'); | |
/** | |
* implicitRoutes hook | |
* | |
* | |
* @description :: A hook definition. Extends Sails by adding shadow routes, implicit actions, and/or initialization logic. | |
* @docs :: https://sailsjs.com/docs/concepts/extending-sails/hooks | |
*/ | |
module.exports = function defineWebpackHook(sails) { | |
return { | |
/** | |
* Runs when this Sails app loads/lifts. | |
*/ | |
initialize: async function (done) { | |
sails.log.info('Initializing custom hook (`implicitRoutes`)'); | |
for (const [routeAddress, routeTarget] of Object.entries(routes)) { | |
if (!routeTarget.isImplicitRoute) continue; | |
const routePath = routeAddress.split(' ').pop(); | |
let parentEntityMeta; | |
let childEntityMeta; | |
routePath.split('/').forEach((piece, ix, pieces) => { | |
const previousPiece = pieces[ix - 1]; | |
if (previousPiece) { | |
if (piece.startsWith(':')) { | |
const attr = piece.substring(1); | |
let singular = pluralize(previousPiece, 1); | |
if (singular === 'event') singular = 'affair'; | |
if (singular === 'flyer') singular = 'ad'; | |
if (singular === 'flyer-request') singular = 'ad-request'; | |
const modelIdentity = singular.replace('-', ''); | |
const localName = camelCase(singular); | |
if (!parentEntityMeta) { | |
parentEntityMeta = { | |
modelIdentity, | |
attr, | |
localName, | |
}; | |
} else if (!childEntityMeta) { | |
childEntityMeta = { | |
modelIdentity, | |
attr, | |
localName, | |
}; | |
} | |
} | |
} | |
}); | |
routeTarget.implicate = async function (req, res, next) { | |
if (parentEntityMeta) { | |
const { modelIdentity, localName, attr } = parentEntityMeta; | |
const parentEntity = await sails.models[modelIdentity].findOne({ | |
[attr]: req.allParams()[attr], | |
}); | |
req[localName] = parentEntity; | |
if (!parentEntity) { | |
return res.notFound(); | |
} | |
if (childEntityMeta) { | |
const { modelIdentity, localName, attr } = childEntityMeta; | |
const childEntity = await sails.models[modelIdentity].findOne({ | |
[attr]: req.allParams()[attr], | |
}); | |
req[localName] = childEntity; | |
if (!childEntity) { | |
return res.notFound(); | |
} | |
// TODO: ensure childEntity belongs to parentEntity | |
} | |
} | |
next(); | |
}; | |
} | |
sails.registerActionMiddleware( | |
function (req, res, next) { | |
return req.options.implicate(req, res, next); | |
}, | |
['*'] | |
); | |
done(); | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment