strapi/packages/strapi-connector-bookshelf/lib/generate-component-relations.js

80 lines
2.3 KiB
JavaScript
Raw Normal View History

2019-07-01 16:59:14 +02:00
'use strict';
const pluralize = require('pluralize');
2019-10-22 18:01:03 +02:00
const createComponentModels = async ({ model, definition, ORM, GLOBALS }) => {
2019-07-01 16:59:14 +02:00
const { collectionName, primaryKey } = definition;
2019-10-22 18:01:03 +02:00
const componentAttributes = Object.keys(definition.attributes).filter(
key => definition.attributes[key].type === 'component'
2019-07-01 16:59:14 +02:00
);
2019-10-22 18:01:03 +02:00
if (componentAttributes.length > 0) {
// create component model
const joinTable = `${collectionName}_components`;
2019-07-01 16:59:14 +02:00
const joinColumn = `${pluralize.singular(collectionName)}_${primaryKey}`;
const joinModel = ORM.Model.extend({
requireFetch: false,
2019-07-08 18:35:39 +02:00
tableName: joinTable,
2019-10-22 18:01:03 +02:00
component() {
2019-07-01 16:59:14 +02:00
return this.morphTo(
2019-10-22 18:01:03 +02:00
'component',
...componentAttributes.map(key => {
const componentKey = definition.attributes[key].component;
return GLOBALS[strapi.components[componentKey].globalId];
2019-07-01 16:59:14 +02:00
})
);
},
});
2019-07-09 18:20:36 +02:00
joinModel.foreignKey = joinColumn;
2019-10-22 18:01:03 +02:00
definition.componentsJoinModel = joinModel;
2019-07-09 18:20:36 +02:00
2019-10-22 18:01:03 +02:00
componentAttributes.forEach(name => {
2019-07-09 18:20:36 +02:00
model[name] = function relation() {
2019-07-01 16:59:14 +02:00
return this.hasMany(joinModel).query(qb => {
qb.where('field', name).orderBy('order');
});
};
});
}
};
2019-10-22 18:01:03 +02:00
const createComponentJoinTables = async ({ definition, ORM }) => {
const { collectionName, primaryKey } = definition;
2019-10-22 18:01:03 +02:00
const componentAttributes = Object.keys(definition.attributes).filter(
key => definition.attributes[key].type === 'component'
);
2019-10-22 18:01:03 +02:00
if (componentAttributes.length > 0) {
const joinTable = `${collectionName}_components`;
const joinColumn = `${pluralize.singular(collectionName)}_${primaryKey}`;
2019-07-01 16:59:14 +02:00
if (await ORM.knex.schema.hasTable(joinTable)) return;
await ORM.knex.schema.createTable(joinTable, table => {
2019-07-01 16:59:14 +02:00
table.increments();
table.string('field').notNullable();
table
.integer('order')
.unsigned()
.notNullable();
2019-10-22 18:01:03 +02:00
table.string('component_type').notNullable();
table.integer('component_id').notNullable();
table.integer(joinColumn).notNullable();
2019-07-01 16:59:14 +02:00
table
.foreign(joinColumn)
.references(primaryKey)
.inTable(collectionName)
.onDelete('CASCADE');
});
}
};
module.exports = {
2019-10-22 18:01:03 +02:00
createComponentModels,
createComponentJoinTables,
};