feat: improve database.sync()

This commit is contained in:
chenos 2021-01-14 10:35:15 +08:00
parent c5f089d7b7
commit 1242ba5aed
7 changed files with 83 additions and 1 deletions

View File

@ -2,6 +2,7 @@ import { getDatabase } from './';
import Database from '../database';
import Table from '../table';
import Model from '../model';
import path from 'path';
let db: Database;
@ -243,6 +244,24 @@ describe('tables', () => {
});
});
describe.only('#import()', () => {
it('import tables', () => {
const tables = db.import({
directory: path.resolve(__dirname, './tables'),
});
expect([...tables.keys()]).toEqual(['demos', 'examples', 'tests']);
expect(db.getTable('demos').getOptions()).toEqual({
name: 'demos', actions: [ { name: 'create' }, { name: 'list' } ]
});
expect(db.getTable('examples').getOptions()).toEqual({
name: 'examples', actions: [ { name: 'create' } ]
});
expect(db.getTable('tests').getOptions()).toEqual({
name: 'tests', actions: [ { name: 'list' } ]
});
});
});
describe('associations', () => {
beforeAll(() => {
});

View File

@ -0,0 +1,8 @@
export default {
name: 'demos',
actions: [
{
name: 'create',
},
],
};

View File

@ -0,0 +1,8 @@
{
"name": "examples",
"actions": [
{
"name": "create"
}
]
}

View File

@ -0,0 +1,12 @@
import { extend } from "../../database";
export default extend({
name: 'demos',
actions: [
{
name: 'list',
},
],
}, {
arrayMerge: (t, s) => t.concat(s),
});

View File

@ -0,0 +1,8 @@
module.exports = {
name: 'tests',
actions: [
{
name: 'create',
},
],
};

View File

@ -0,0 +1,8 @@
export default {
name: 'tests',
actions: [
{
name: 'list',
},
],
};

View File

@ -35,6 +35,19 @@ export interface DatabaseOptions extends Options {
export type HookType = 'beforeTableInit' | 'afterTableInit' | 'beforeAddField' | 'afterAddField';
export class Extend {
tableOptions: TableOptions;
mergeOptions: MergeOptions
constructor(tableOptions: TableOptions, mergeOptions?: MergeOptions) {
this.tableOptions = tableOptions;
this.mergeOptions = mergeOptions;
}
}
export function extend(tableOptions: TableOptions, mergeOptions: MergeOptions = {}) {
return new Extend(tableOptions, mergeOptions);
}
export default class Database {
public readonly sequelize: Sequelize;
@ -80,7 +93,13 @@ export default class Database {
const tables = new Map<string, Table>();
files.forEach((file: string) => {
const result = requireModule(file);
this.extend(typeof result === 'function' ? result(this) : result);
if (result instanceof Extend) {
const table = this.extend(result.tableOptions, result.mergeOptions);
tables.set(table.getName(), table);
} else {
const table = this.extend(typeof result === 'function' ? result(this) : result);
tables.set(table.getName(), table);
}
});
return tables;
}