Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(update): automatically identify pk and fks into repository layer #150

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions src/generators/src/infra/database/repositories/repositories.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,55 @@ const camelCase = require('lodash.camelcase')
const fs = require('fs')
const path = require('path')

const types = {String , Boolean, Number, undefined, Symbol, Object, Null: null}

function generateForeignKeysField(schema) {
const idFieldsNames = {}
Object.values(schema).map(field => {
if (types[field.type.name]) return

const { schema, name } = field.type.prototype.meta

Object.values(schema).map(idFields => {
if(idFields.options.isId)
idFieldsNames[`${camelCase(name)}_${idFields.name}`] = idFields.type.name
})
})
return idFieldsNames
}

async function generateRepositories(generate, filesystem, db, command) {
const requires = {}

const herbarium = requireHerbarium(command, filesystem.cwd())
const entities = herbarium.entities.all

for (const entity of Array.from(entities.values())) {
const { name } = entity.entity.prototype.meta
const { name, schema } = entity.entity.prototype.meta
const lowCCName = camelCase(name)
const repositoryPath = path.normalize(`${filesystem.cwd()}/src/infra/data/repositories/${lowCCName}Repository.js`)
let foreignKeysFields
const primaryKeyFields = []
Object.values(schema).filter(idFields => {
if(idFields.options.isId)
primaryKeyFields.push(idFields.name)
})

requires[`${lowCCName}Repository`] = `await new (require('./${lowCCName}Repository.js'))(conn)`

if (fs.existsSync(repositoryPath)) continue

if (db !== 'mongo') foreignKeysFields = generateForeignKeysField(schema)

await generate({
template: `infra/data/repository/${db}/repository.ejs`,
target: repositoryPath,
props: {
name: {
pascalCase: name,
camelCase: lowCCName
camelCase: lowCCName,
},
primaryKeyFields,
foreignKeysFields,
table: `${lowCCName}s`
}
})
Expand Down
4 changes: 3 additions & 1 deletion src/templates/infra/data/repository/mysql/repository.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ class <%- props.name.pascalCase %>Repository extends Repository {
super({
entity: <%- props.name.pascalCase %>,
table: "<%- props.table %>",
knex: connection
ids: [<% for (const [index, value] of Object.entries(props.primaryKeyFields)) { %><%if(index != 0) { %>, <% } %>'<%= value %>'<% } %>],
knex: connection<%if(Object.values(props.foreignKeysFields).length) {%>,
foreignKeys: [{ <% Object.entries(props.foreignKeysFields).forEach(([key, value], index) => {%><%if(index != 0) { %>, <% } %><%= key %>: <%= value %><% }) %> }]<% }%>
})
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/templates/infra/data/repository/postgres/repository.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ class <%- props.name.pascalCase %>Repository extends Repository {
super({
entity: <%- props.name.pascalCase %>,
table: "<%- props.table %>",
knex: connection
ids: [<% for (const [index, value] of Object.entries(props.primaryKeyFields)) { %><%if(index != 0) { %>, <% } %>'<%= value %>'<% } %>],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part of the code seems duplicated in other files.

I think this should be refactored

knex: connection<%if(Object.values(props.foreignKeysFields).length) {%>,
foreignKeys: [{ <% Object.entries(props.foreignKeysFields).forEach(([key, value], index) => {%><%if(index != 0) { %>, <% } %><%= key %>: <%= value %><% }) %> }]<% }%>
})
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/templates/infra/data/repository/sqlserver/repository.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ class <%- props.name.pascalCase %>Repository extends Repository {
super({
entity: <%- props.name.pascalCase %>,
table: "<%- props.table %>",
knex: connection
ids: [<% for (const [index, value] of Object.entries(props.primaryKeyFields)) { %><%if(index != 0) { %>, <% } %>'<%= value %>'<% } %>],
knex: connection<%if(Object.values(props.foreignKeysFields).length) {%>,
foreignKeys: [{ <% Object.entries(props.foreignKeysFields).forEach(([key, value], index) => {%><%if(index != 0) { %>, <% } %><%= key %>: <%= value %><% }) %> }]<% }%>
})
}
}
Expand Down
49 changes: 49 additions & 0 deletions src/tests/repositories.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/* globals describe, it, afterEach */

const { system } = require('gluegun')
const { expect } = require('chai')
const fs = require('fs')
const path = require('path')

const projectName = 'herbs-test-runner'

const generateProject = () => system.run(`herbs new --name ${projectName} --description "testing the herbs CLI" --author herbs --license MIT --graphql --rest no --database postgres --npmInstall yes`)
const callHerbsCli = () => system.run(`herbs`)

const herbsUpdate = () => system.run(`cd ${projectName} && herbs update`)

describe('When I generate a complete project that uses postgres', () => {
afterEach(async () => {
fs.rmSync(path.resolve(process.cwd(), `${projectName}`), { recursive: true })
})

it('Should I create a new repository with foreign key', async () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be a test without the foreing key

await generateProject()
await callHerbsCli()
const customerEntity =
`
const { entity, id, field } = require('@herbsjs/herbs')
const { herbarium } = require('@herbsjs/herbarium')
const User = require('./user')

const Customer =
entity('Customer', {
id: id(String),
description: field(String),
user: field(User)
})

module.exports =
herbarium.entities
.add(Customer, 'Customer')
.entity
`

const dir = `${path.resolve(process.cwd(), `${projectName}/src/domain/entities/customer.js`)}`
fs.writeFileSync(dir, customerEntity)
expect(fs.existsSync(dir)).to.be.true
await herbsUpdate()
expect(fs.existsSync(path.resolve(process.cwd(), `${projectName}/src/infra/data/repositories/customerRepository.js`))).to.be.true
})
})

1 change: 0 additions & 1 deletion src/tests/shell.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const path = require('path')
const fs = require('fs')
const { expect } = require('chai')
const projectName = 'herbs-test-runner'
const { exec } = require('node:child_process')

const linknpm = () => system.run(`cd bin && npm link --force`)
const generateProject = () => system.run(`herbs new --name ${projectName} --description "testing the herbs CLI" --author herbs --license MIT --graphql --rest --database mongo --npmInstall yes`)
Expand Down