Commit 7bf8137f authored by Jarrod's avatar Jarrod 💬

Event handlers; `sdk:` tag on routes

parent d874b5b8
Pipeline #4240 passed with stage
in 44 seconds
......@@ -33,7 +33,7 @@ module.exports = {
// We determine its name using the bare action name.
var bareActionName = target.action.replace(/\//g, '-')
var methodName = target.name || _.camelCase(bareActionName)
var methodName = target.sdk || target.name || _.camelCase(bareActionName)
var expandedAddress = sails.getRouteFor(target)
// Skip routes that just serve views.
......
......@@ -8,7 +8,7 @@ const cacheMiddleware = require('./middleware/cache')
module.exports = class SailsPluggable {
constructor (opt = {}) {
this.opt = opt
// FUTURE MAYBE: Can probably guess this based on the upstream hooks folder name?
// FUTURE MAYBE: `key` Can probably guess this based on the upstream hooks folder name?
this.opt.key = this.opt.key || this.opt.apiBase
this.core = this.opt.key === 'ahoy'
this.log = function () { sails.log[sails.hooks.ahoy.logLevel || 'info'](...arguments) }
......@@ -33,6 +33,7 @@ module.exports = class SailsPluggable {
await this.registerActions()
await this.registerModels()
await this.registerEventHandlers()
if (this.opt.initialize) {
await this.opt.initialize()
......@@ -52,13 +53,14 @@ module.exports = class SailsPluggable {
if (def.extend) {
_.each(def.extend, (attributes, name) => {
sails.log.info(`Ahoy: Extending ${name}`, attributes)
const model = sails.config.orm.moduleDefinitions.models[name] // || sails.models[name]
const model = sails.config.orm.moduleDefinitions.models[name] || sails.models[name] // || sails.models[name]
if (!model || !model.attributes) {
sails.log.error(`Unable to extend model ${name} from ${extender}`)
sails.log.error(`Unable to extend model ${name} from ${extender}`, { model})
} else {
_.each(attributes, (opt, field) => {
(sails.config.orm.moduleDefinitions.models[name] || sails.models[name]).attributes[field] = opt
})
}
_.each(attributes, (opt, field) => {
sails.config.orm.moduleDefinitions.models[name].attributes[field] = opt
})
})
}
})
......@@ -66,7 +68,12 @@ module.exports = class SailsPluggable {
// Reload the Sails ORM
sails.hooks.orm.reload((err) => {
if (err) { sails.log.error(`Unable to reload sails ORM`, err.stack) }
sails.emit('ahoy:ready')
console.log(`Running sails migrations (again?) ${sails.config.models.migrate}`)
const wlUtils = require('waterline-utils')
wlUtils.autoMigrations(sails.config.models.migrate, sails.hooks.orm._orm, function onAutoMigrationsManuallyTriggered () {
sails.emit('ahoy:ready')
})
})
// Retrofit our route-level middlewares
......@@ -74,15 +81,13 @@ module.exports = class SailsPluggable {
_.each(sails.config.routes, (def, path) => {
if (!def.action) { return }
// TODO: Will this work in the upstream auth modules? Might / should.. time will tell.
// If/when it does get rid of this commented junkskie :)
// if (def.auth || def.permission) {
// sails.log.verbose('Initializing permissions middleare for ', path)
// sails.registerActionMiddleware(permissionsMiddleware, def.action)
// }
if ('auth' in sails.hooks && _.isFunction(sails.config.auth.permissionsMiddleware)) {
sails.log.verbose('Binding permissions middleware to: ', path)
sails.registerActionMiddleware(sails.config.auth.permissionsMiddleware, def.action)
}
if (def.cache) {
sails.log.verbose('Initializing cache middleware for ', path)
sails.log.verbose('Initializing cache middleware to: ', path)
sails.registerActionMiddleware(cacheMiddleware, def.action)
}
})
......@@ -121,8 +126,8 @@ module.exports = class SailsPluggable {
})
}
async registerModels () {
const modelDir = path.join(this.opt.dir, 'models')
async registerModels (_dirOverride) {
const modelDir = _dirOverride || path.join(this.opt.dir, 'models')
if (!fs.existsSync(modelDir)) {
return
}
......@@ -141,7 +146,7 @@ module.exports = class SailsPluggable {
// Check for model collisions. In theory userland models should take preference/override the core Ahoy user model
if (sails.models[lcName] || sails.config.orm.moduleDefinitions.models[lcName]) {
sails.log.warn(`Ahoy: Skip loading model "${name}" as it already exists on the Sails instance (this *could* be the expected behaviour if you have created a userland model with the name ${name}, but could also be attributed to ahoy plugin model collisons.)`)
sails.log.debug(`Ahoy: Skip loading model "${name}" from '${this.opt.key}' as it already exists on the Sails instance (this *could* be the expected behaviour if you have created a userland model with the name ${name}, but could also be attributed to ahoy plugin model collisons or some other cancerous nonsense.)`)
return
}
......@@ -152,6 +157,39 @@ module.exports = class SailsPluggable {
})
}
registerEventHandlers () {
const modelDir = path.join(this.opt.dir, 'event-handlers')
if (!fs.existsSync(modelDir)) {
return
}
const models = includeAll({
dirname : modelDir,
filter : /(.*)\.js$/
})
if (_.isEmpty(models)) {
return
}
_.each(models, (def, name) => {
if (_.isString(def.event)) {
def.event = [def.event]
}
def.event.forEach(e => {
if (!_.isString(e) || _.isEmpty(e) || !_.isFunction(def.fn)) {
sails.log.error(`Unable to initialize event handler [${e}] from Ahoy pluggable [${this.opt.key}] - Invalid definition\n`
+ ` Event handler should contain keys:\n - 'event' string|array event name(s), ie 'ahoy:reporting:create'\n`
+ ` - 'fn' event handler method`)
return
}
sails.log.debug(`Initializing event handler from [${this.opt.key}] - ${e}`)
sails.on(e, def.fn)
})
})
}
toHook () {
const that = this
return function (sails) {
......@@ -176,6 +214,9 @@ module.exports = class SailsPluggable {
}
}
// Bodge on userland models
that.registerModels(sails.config.paths.models)
// Find other Ahoy hooks
_.each(sails.hooks, (hook, name) => {
if (hook.ahoy) {
......
{
"name": "@nahanil/ahoy",
"version": "0.1.0",
"version": "0.1.1",
"description": "",
"main": "lib/index.js",
"scripts": {
......@@ -15,12 +15,10 @@
"author": "Jarrod Linahan <jarrod@linahan.id.au>",
"license": "MIT",
"dependencies": {
"@nahanil/sails-hook-api-log": "^1.0.0",
"@sailshq/lodash": "^3.10.3",
"axios": "^0.19.2",
"mailgun-js": "^0.22.0",
"memory-cache": "^0.2.0",
"sails": "^1.2.3",
"sails-hook-orm": "^2.1.1",
"uuid": "^3.3.2"
},
"devDependencies": {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment