1.3.2 • Published 7 years ago
model-loader v1.3.2
Installation
npm install koa-orm
Example
Single database
const path = require('path')
const config = {
modelPath: path.resolve(__dirname, 'models'),
migrationPath: path.resolve(__dirname, 'database/migrations'),
db: 'db_test',
username: 'postgres',
options: {
dialect: 'postgres',
logging: true,
},
password: 'pass',
host: '127.0.0.1',
port: 5432,
}
app.context.db = await require('model-loader')(config)
app.use('SomeService', 'someList', async function(ctx) {
const result = await ctx
.db
.sql.select()
.from('table')
.query()
ctx.res = result
})
Multiple database
const join = require('path').join
const configs = [
{
modelPath: path.resolve(__dirname, 'model/cohorts'),
migrationPath: path.resolve(__dirname, 'database/migrations/cohort'),
db: 'cohort',
username: 'postgres',
options: {
dialect: 'postgres',
logging: true,
},
password: 'pass',
host: '127.0.0.1',
port: 5432,
}
{
modelPath: path.resolve(__dirname, 'models/location'),
migrationPath: path.resolve(__dirname, 'database/migrations/location'),
db: 'location',
username: 'postgres',
options: {
dialect: 'postgres',
logging: true,
},
password: 'pass',
host: '127.0.0.1',
port: 5432,
}
]
app.context.db = await require('model-loader')(config)
app.use('SomeService', 'someList', async function(ctx) {
const Cohort = ctx.db.cohort.Cohort
const Location = ctx.db.location.Location
const payload = ctx.request.req
const cohort = new Cohort(payload)
await cohort.save()
// cohort.location = ctx.db.location.sql.select().from('locations').where('id = ?', cohort.locationId).query()
cohort.location = await Location.findById(cohort.locationId)
ctx.res = cohort
})
API
await modeLoader(configs)
configs
: Multi database config array.
yarn add model-loader@latest