Skip to content

Instantly share code, notes, and snippets.

@cfv1984
Created May 31, 2021 18:35
Show Gist options
  • Save cfv1984/71dae877b2c33a8bc9c41a758b8cf578 to your computer and use it in GitHub Desktop.
Save cfv1984/71dae877b2c33a8bc9c41a758b8cf578 to your computer and use it in GitHub Desktop.
Xanthan: A cute, declarative way to graft methods to specific Sequelize instances behind feature flags
/**
* Xanthan is a cute declarative way to compose different sets of traits onto Sequelize models
*
* It is distributed under the terms of the WTFPL (http://www.wtfpl.net/about/)
*
* Usage:
* const {Sequelize, DataTypes: { TEXT, INTEGER } } = require('sequelize');
* const { getFoo, setFoo } = require('./expandos/foo');
* require('./xanthan')(Sequelize)({
* isFoo: { // this means only models that pass an `isFoo: true` option will get the methods below grafted to them
* getFoo,
* setFoo
* }
* });
* const connection = new Sequelize("sqlite::memory:");
* const Foos = connection.define("foos", {
* id: {
* type: INTEGER,
* primaryKey: true,
* autoIncrement: true
* },
* content: {
* type: TEXT,
* allowNull: false
* }
* }, { isFoo: true} );
* // Foos now has getFoo and setFoo instance methods.
*/
module.exports = function xanthan(Sequelize) {
return function (features) {
Sequelize.addHook("afterInit", function (connection) {
connection.addHook("afterDefine", function (model) {
for (let feature in features) {
const expandos = features[feature];
const hasFeature = feature in model.options;
const isFeatureEnabled =
hasFeature && model.options[feature] === true;
if (isFeatureEnabled) {
for (let expando in expandos) {
model.prototype[expando] = expandos[expando];
}
}
}
});
});
};
};
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment