simple seed is working

This commit is contained in:
Moriz Wahl 2021-11-18 19:17:51 +01:00
parent 15d1e6545b
commit 0b3ead8369
6 changed files with 34 additions and 5 deletions

View File

@ -4,4 +4,6 @@ DB_USER=root
DB_PASSWORD=
DB_DATABASE=gradido_community
MIGRATIONS_TABLE=migrations
MIGRATIONS_DIRECTORY=./migrations/
MIGRATIONS_DIRECTORY=./migrations/
TYPEORM_SEEDING_FACTORIES=src/factories/**/*{.ts,.js}

15
database/ormconfig.js Normal file
View File

@ -0,0 +1,15 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const CONFIG = require('./src/config')
module.export = {
name: 'default',
type: 'mysql',
host: CONFIG.DB_HOST,
port: CONFIG.DB_PORT,
username: CONFIG.DB_USER,
password: CONFIG.DB_PASSWORD,
database: CONFIG.DB_DATABASE,
seeds: ['src/seeds/**/*{.ts,.js}'],
factories: ['src/factories/**/*{.ts,.js}'],
}

View File

@ -16,7 +16,9 @@
"dev_up": "nodemon -w ./ --ext ts --exec ts-node src/index.ts up",
"dev_down": "nodemon -w ./ --ext ts --exec ts-node src/index.ts down",
"dev_reset": "nodemon -w ./ --ext ts --exec ts-node src/index.ts reset",
"lint": "eslint . --ext .js,.ts"
"lint": "eslint . --ext .js,.ts",
"seed:config": "ts-node ./node_modules/typeorm-seeding/dist/cli.js config",
"seed": "nodemon -w ./ --ext ts --exec ts-node src/index.ts seed"
},
"devDependencies": {
"@types/faker": "^5.5.9",

View File

@ -12,9 +12,10 @@ interface UserContext {
disabled?: boolean
}
define(User, (faker: typeof Faker, context: UserContext) => {
const user = new User()
define(User, (faker: typeof Faker, context?: UserContext) => {
if (!context) context = {}
const user = new User()
user.pubkey = context.pubkey ? context.pubkey : randomBytes(32)
user.email = context.email ? context.email : faker.internet.email()
user.firstName = context.firstName ? context.firstName : faker.name.firstName()

View File

@ -4,6 +4,8 @@ import { Migration } from 'ts-mysql-migrate'
import CONFIG from './config'
import prepare from './prepare'
import connection from './typeorm/connection'
import { useSeeding, runSeeder } from 'typeorm-seeding'
import { CreateUserSeed } from './seeds/create-user.seed'
const run = async (command: string) => {
// Database actions not supported by our migration library
@ -47,6 +49,13 @@ const run = async (command: string) => {
case 'reset':
await migration.reset() // use for resetting database
break
case 'seed':
await useSeeding({
root: process.cwd(),
configName: 'ormconfig.js',
})
await runSeeder(CreateUserSeed)
break
default:
throw new Error(`Unsupported command ${command}`)
}

View File

@ -1,7 +1,7 @@
import { Factory, Seeder } from 'typeorm-seeding'
import { User } from '../../entity/User'
export class CreateUser implements Seeder {
export class CreateUserSeed implements Seeder {
public async run(factory: Factory): Promise<void> {
await factory(User)().create()
}