egg-knex-model
a knex plugin for egg.js
Usage
- Run
npm i egg-knex-model
- Enable
egg-knex-model
{
knex: {
enable: true,
package: 'egg-knex-model',
},
}
- Configure
egg-knex-model
in config/config.default.ts
{
knex: {
client: {
client: 'pg',
version: '7.2',
connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test'
}
},
app: true,
agent: false,
},
}
- Configure
egg-ts-helper
in package.json
(TypeScript ONLY)
{
"egg": {
"typescript": true,
"tsHelper": {
"watchDirs": {
"model": {
"pattern": "**/*.(ts|js)",
"path": "app/model",
"generator": "class",
"interface": "IModel",
"caseStyle": "lower",
"trigger": [
"add",
"unlink"
],
"interfaceHandle": false
}
}
}
}
}
- Add model in
app/model
import { BaseModel, BaseEntity } from 'egg-knex-model';
interface E extends BaseEntity {
username:string;
points:number;
}
export default class extends BaseModel<E> {
protected tableName = 'user';
getByUsername(username:string) {
return this.getOne({username});
}
}
- Use model
export default class Test extends Service {
public async test() {
await this.app.knex.trx(async model => {
await model.user.insert({
username: '23333',
points: 100,
});
await model.user.increment({ username: '23333'}, 'points');
});
console.log(await this.app.model.user.getOne({
username: '23333',
}));
try {
await this.app.knex.trx(async model => {
await model.user.update({}, { username: '555555' });
throw new Error('this transaction should be rolled back');
});
} catch (e) {
console.error(e);
}
}
}