85 lines
2.4 KiB
JavaScript
85 lines
2.4 KiB
JavaScript
// 3rd party.
|
|
const {createDispatcher, invokeHookFlat} = require('@truss/comm');
|
|
const Waterline = require('waterline');
|
|
const {getGraphQLSchemaFrom} = require('waterline-to-graphql');
|
|
// Instance of waterline.
|
|
const waterline = new Waterline();
|
|
// Dispatcher.
|
|
const dispatcher = createDispatcher();
|
|
dispatcher.lookupActions(require('./actions'));
|
|
dispatcher.lookupHooks(require('./hooks'));
|
|
// Connect dispatcher.
|
|
dispatcher.connect();
|
|
// Gather and register collections.
|
|
invokeHookFlat('ormCollections').then((serviceCollections) => {
|
|
for (const collections of serviceCollections) {
|
|
for (collection of collections) {
|
|
waterline.registerModel(Waterline.Collection.extend(collection));
|
|
}
|
|
}
|
|
// Adapter config.
|
|
const sailsDiskAdapter = require('sails-disk');
|
|
const config = {
|
|
adapters: {
|
|
disk: sailsDiskAdapter,
|
|
},
|
|
datastores: {
|
|
default: {
|
|
adapter: 'disk',
|
|
},
|
|
},
|
|
};
|
|
// Initialize waterline.
|
|
waterline.initialize(config, async (error, ontology) => {
|
|
if (error) {
|
|
return console.error(error);
|
|
}
|
|
const models = ontology.collections || [];
|
|
setupAssociations(models);
|
|
const schema = getGraphQLSchemaFrom(models);
|
|
dispatcher.setArgs(schema);
|
|
dispatcher.lookupActions(require('./actions'));
|
|
dispatcher.lookupHooks(require('./hooks'));
|
|
if (module.hot) {
|
|
module.hot.accept('./actions', () => {
|
|
dispatcher.lookupActions(require('./actions'));
|
|
});
|
|
module.hot.accept('./hooks', () => {
|
|
dispatcher.lookupHooks(require('./hooks'));
|
|
});
|
|
}
|
|
});
|
|
});
|
|
|
|
function setupAssociations(models) {
|
|
for (const id in models) {
|
|
const model = models[id];
|
|
model._attributes = model.attributes;
|
|
const associations = [];
|
|
for (const name in model.attributes) {
|
|
const attribute = model.attributes[name];
|
|
if ('object' !== typeof attribute) {
|
|
continue;
|
|
}
|
|
if (!attribute.model && !attribute.collection) {
|
|
continue;
|
|
}
|
|
var association = {
|
|
alias: name,
|
|
type: attribute.model ? 'model' : 'collection',
|
|
};
|
|
if (attribute.model) {
|
|
association.model = attribute.model;
|
|
}
|
|
if (attribute.collection) {
|
|
association.collection = attribute.collection;
|
|
}
|
|
if (attribute.via) {
|
|
association.via = attribute.via;
|
|
}
|
|
associations.push(association);
|
|
}
|
|
model.associations = associations;
|
|
}
|
|
}
|