Skip to content

Commit

Permalink
feat: integrate Objection for ActiveRecord (sodacitylabs#124)
Browse files Browse the repository at this point in the history
  • Loading branch information
gfogle authored Nov 20, 2019
1 parent 1571652 commit 898976b
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 387 deletions.
30 changes: 29 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,14 @@
"fastify": "2.10.0",
"fastify-static": "2.5.0",
"jest": "24.9.0",
"knex": "0.19.1",
"lodash": "4.17.15",
"maildev": "1.1.0",
"nodemailer": "6.3.0",
"nodemailer-html-to-text": "3.0.0",
"nodemailer-ses-transport": "1.5.1",
"nodemailer-smtp-transport": "2.7.4",
"objection": "1.6.11",
"pluralize": "7.0.0",
"request": "2.88.0",
"request-promise-native": "1.0.7",
Expand Down Expand Up @@ -80,9 +82,9 @@
"coverageDirectory": "<rootDir>/coverage",
"collectCoverageFrom": [
"src/core/**/*.js*",
"!src/core/index.js",
"!src/core/Database.js",
"!src/core/ActiveRecord.js",
"!src/core/ActiveRecordCache.js",
"!src/core/Mailer.js",
"!src/core/RouterV2.js",
"!src/core/RequestController.js",
Expand Down
73 changes: 53 additions & 20 deletions src/cli/generate/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,27 +62,28 @@ module.exports = async function(dir, name, attrs) {

let belongsTo = [];

const tableName = NounHelper.toPluralResource(name);
const modelName = NounHelper.getSingularForm(name);

fs.writeFileSync(
migrationFile,
`
exports.up = async function(knex) {
await knex.schema.dropTableIfExists('${NounHelper.toPluralResource(
name
)}');
await knex.schema.createTable('${NounHelper.toPluralResource(
name
)}', (table) => {
await knex.schema.dropTableIfExists('${tableName}');
await knex.schema.createTable('${tableName}', (table) => {
table.bigIncrements('id').primary();
${attrs.reduce((acc, curr) => {
if (curr.type !== "references") {
acc += `table.${curr.type}('${curr.name}');\n`;
}
if (curr.type === "references") {
belongsTo.push(`${NounHelper.toPluralResource(curr.name)}`);
belongsTo.push(`${curr.name}`);
acc += `table.bigInteger('${NounHelper.toSingularResource(
curr.name
)}_id').notNullable();\n`;
acc += `table.foreign("${NounHelper.toSingularResource(
curr.name
)}_id").references("id").inTable("${NounHelper.toPluralResource(
Expand All @@ -105,25 +106,20 @@ module.exports = async function(dir, name, attrs) {
"utf8"
);

const belongsToRelations =
belongsTo.length && _buildBelongsToRelation(modelName, belongsTo);

fs.writeFileSync(
modelFile,
`
const Boring = require('@sodacitylabs/boring-framework');
const ActiveRecord = Boring.Model.ActiveRecord;
${(belongsTo.length &&
belongsTo.reduce((acc, curr) => `const ${curr} = require('./${curr}')`),
"")}
module.exports = class ${NounHelper.getSingularForm(
name
)} extends ActiveRecord {
constructor(attrs) {
super(attrs);
}
${
belongsTo.length
? `get belongsTo() {
return ${JSON.stringify(belongsTo)};
}`
: "get belongsTo() { return []; }"
}
module.exports = class ${modelName} extends ActiveRecord {
${belongsTo.length && belongsToRelations}
};
`,
"utf8"
Expand All @@ -143,6 +139,8 @@ module.exports = async function(dir, name, attrs) {
"utf8"
);

// TODO: write the inverse relation mapping to the parent?

spawnSync(`${dir}/node_modules/.bin/prettier "${migrationFile}" --write`, {
stdio: `inherit`,
shell: true,
Expand All @@ -159,3 +157,38 @@ module.exports = async function(dir, name, attrs) {
cwd: dir
});
};

/**
*
* @param {*} sourceModel the source model ie. "Comment"
* @param {*} relatedModels array of related models ie. ["BlogPost"]
*/
function _buildBelongsToRelation(sourceModel, relatedModels) {
const relationsAsString = relatedModels.reduce((acc, curr) => {
const camelizedRelatedModelName = NounHelper.getCamelCaseSingularForm(curr);
const sourceTableName = NounHelper.toPluralResource(sourceModel);
const relatedIdColumnName = `${NounHelper.toSingularResource(curr)}_id`;
const relatedTableName = NounHelper.toPluralResource(curr);

acc += `
${camelizedRelatedModelName}: {
relation: ActiveRecord.BelongsToOneRelation,
modelClass: ${curr},
join: {
from: '${sourceTableName}.${relatedIdColumnName}',
to: '${relatedTableName}.id'
}
}
`;

return acc;
}, "");

return `
static get relationMappings() {
return {
${relationsAsString}
};
};
`;
}
Loading

0 comments on commit 898976b

Please sign in to comment.