2022-02-14 16:20:25 +00:00
|
|
|
import { merge, uid } from '@nocobase/utils';
|
|
|
|
import { resolve } from 'path';
|
|
|
|
import { Database, IDatabaseOptions } from './database';
|
|
|
|
|
|
|
|
export class MockDatabase extends Database {
|
|
|
|
constructor(options: IDatabaseOptions) {
|
|
|
|
super({
|
|
|
|
storage: ':memory:',
|
|
|
|
tablePrefix: `mock_${uid(6)}_`,
|
2022-03-28 14:01:10 +00:00
|
|
|
dialect: 'sqlite',
|
2022-02-14 16:20:25 +00:00
|
|
|
...options,
|
|
|
|
});
|
|
|
|
this.sequelize.beforeDefine((model, opts) => {
|
|
|
|
opts.tableName = `${this.getTablePrefix()}${opts.tableName || opts.modelName || opts.name.plural}`;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getConfigByEnv() {
|
|
|
|
return {
|
|
|
|
username: process.env.DB_USER,
|
|
|
|
password: process.env.DB_PASSWORD,
|
|
|
|
database: process.env.DB_DATABASE,
|
|
|
|
host: process.env.DB_HOST,
|
|
|
|
port: process.env.DB_PORT,
|
|
|
|
dialect: process.env.DB_DIALECT,
|
|
|
|
logging: process.env.DB_LOG_SQL === 'on' ? console.log : false,
|
2022-03-28 14:01:10 +00:00
|
|
|
storage:
|
|
|
|
process.env.DB_STORAGE && process.env.DB_STORAGE !== ':memory:'
|
|
|
|
? resolve(process.cwd(), process.env.DB_STORAGE)
|
|
|
|
: ':memory:',
|
2022-02-15 14:32:02 +00:00
|
|
|
define: {
|
2022-02-14 16:20:25 +00:00
|
|
|
charset: 'utf8mb4',
|
|
|
|
collate: 'utf8mb4_unicode_ci',
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export function mockDatabase(options: IDatabaseOptions = {}): MockDatabase {
|
2022-03-28 14:01:10 +00:00
|
|
|
const dbOptions = merge(getConfigByEnv(), options);
|
|
|
|
return new MockDatabase(dbOptions);
|
2022-02-14 16:20:25 +00:00
|
|
|
}
|