Skip to content

Instantly share code, notes, and snippets.

@alterx
Last active February 25, 2017 23:23
Show Gist options
  • Save alterx/2ee0399f663daa66eac9205d4a3bc5aa to your computer and use it in GitHub Desktop.
Save alterx/2ee0399f663daa66eac9205d4a3bc5aa to your computer and use it in GitHub Desktop.
Simple Koa 2 middleware that transparently exposes Waterline (node 7.6+)
'use strict';
const Waterline = require('waterline');
let _waterline;
const upper = (str) => str[0].toUpperCase() + str.slice(1);
const isInvalid = (model) => (!model.identity);
const init = async ({ models, adapters, connections }) => {
if (_waterline) return Promise.resolve(_waterline);
_waterline = new Waterline();
models.forEach((model) => {
if (isInvalid(model)) return;
let collection = Waterline.Collection.extend(model);
_waterline.loadCollection(collection);
});
return new Promise((resolve, reject) => {
_waterline.initialize({ adapters, connections }, (err, _) => {
if (err) reject(err);
resolve(_waterline);
});
});
};
module.exports = (config) => {
return async (ctx, next) => {
if (!ctx.waterline) {
const waterline = await init(config);
ctx.waterline = waterline;
}
await next();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment