Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated dependencies, including TypeORM 0.3.10 #235

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ For all entities we want to create, we need to define a factory. To do so we giv

| Types | Description |
| --------------- | ------------------------------------------------------------------------------- |
| `Entity` | TypeORM Entity like the user or the pet in the samples. |
| `Entity` | TypeORM Entity like the user or the pet in the samples. |
| `Context` | Argument to pass some static data into the factory function. |
| `EntityFactory` | This object is used to make new filled entities or create it into the database. |

Expand All @@ -242,7 +242,7 @@ For all entities we want to create, we need to define a factory. To do so we giv
The define function creates a new entity factory.

```typescript
define: <Entity, Context>(entity: Entity, factoryFn: FactoryFunction<Entity, Context>) => void;
define: <Entity extends ObjectLiteral, Context>(entity: Entity, factoryFn: FactoryFunction<Entity, Context>) => void;
```

```typescript
Expand All @@ -258,7 +258,7 @@ define(User, (faker: typeof Faker, context: { roles: string[] }) => { ... })
Factory retrieves the defined factory function and returns the EntityFactory to start creating new enities.

```typescript
factory: (entity: Entity) => (context?: Context) => EntityFactory<Entity, Context>
factory: (entity: Entity extends ObjectLiteral) => (context?: Context) => EntityFactory<Entity, Context>
```

```typescript
Expand All @@ -273,7 +273,7 @@ factory(Pet)({ name: 'Balou' })
Use the `.map()` function to alter the generated value before they get persisted.

```typescript
map(mapFunction: (entity: Entity) => Promise<Entity>): EntityFactory<Entity, Context>
map(mapFunction: (entity: Entity extends ObjectLiteral) => Promise<Entity>): EntityFactory<Entity, Context>
```

```typescript
Expand Down
55 changes: 26 additions & 29 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,42 +32,39 @@
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@semantic-release/git": "^9.0.0",
"@semantic-release/git": "^9.0.1",
"@types/bcryptjs": "^2.4.2",
"@types/chalk": "^2.2.0",
"@types/faker": "^5.5.8",
"@types/glob": "7.1.1",
"@types/jest": "^25.2.1",
"@types/node": "13.11.1",
"@types/yargs": "^15.0.4",
"@typescript-eslint/eslint-plugin": "^2.27.0",
"@typescript-eslint/parser": "^2.27.0",
"@types/faker": "^5.5.3",
"@types/glob": "^8.0.0",
"@types/jest": "^29.0.3",
"@types/node": "16.11.65",
"@types/yargs": "^17.0.3",
"@typescript-eslint/eslint-plugin": "^5.40.0",
"@typescript-eslint/parser": "^5.40.0",
"bcryptjs": "^2.4.3",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.1",
"eslint-plugin-import": "^2.20.2",
"jest": "^25.3.0",
"prettier": "^2.0.4",
"eslint": "^8.25.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"jest": "^29.1.2",
"prettier": "^2.7.1",
"rimraf": "^3.0.2",
"semantic-release": "^17.0.4",
"sqlite": "^4.0.6",
"sqlite3": "^4.1.1",
"ts-jest": "^25.3.1",
"typeorm": "^0.2.24",
"typescript": "^3.8.3"
"semantic-release": "^19.0.5",
"sqlite": "^4.1.2",
"sqlite3": "^5.1.2",
"ts-jest": "^29.0.3",
"typeorm": "^0.3.10",
"typescript": "^4.8.4"
},
"dependencies": {
"chalk": "^4.0.0",
"faker": "5.5.3",
"glob": "7.1.6",
"ora": "4.0.3",
"reflect-metadata": "0.1.13",
"yargs": "15.3.1"
"faker": "^5.5.3",
"glob": "^8.0.3",
"mem": "^9.0.2",
"ora": "^4.0.3",
"reflect-metadata": "^0.1.13",
"yargs": "^17.6.0"
},
"peerDependencies": {
"typeorm": "^0.2.24"
},
"resolutions": {
"mem": ">=4.0.0"
"typeorm": "^0.3.10"
}
}
11 changes: 11 additions & 0 deletions sample/test/datasource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { join } from 'path'
import { DataSource } from 'typeorm'

const ds = new DataSource({
name: 'file',
type: 'sqlite',
database: ':memory:',
entities: ['sample/entities/**/*{.ts,.js}'],
})

export default ds
54 changes: 38 additions & 16 deletions sample/test/sample.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,53 @@ import {
tearDownDatabase,
factory,
setConnectionOptions,
ConnectionOptions,
configureConnection,
} from '../../src/typeorm-seeding'
import { User } from '../entities/User.entity'
import { Connection } from 'typeorm'
import { DataSource } from 'typeorm'
import { join } from 'path'

const inMemoryDb: ConnectionOptions = {
name: 'memory',
type: 'sqlite',
database: ':memory:',
entities: ['sample/entities/**/*{.ts,.js}'],
factories: ['sample/factories/**/*{.ts,.js}'],
seeds: ['sample/seeds/**/*{.ts,.js}'],
}

describe('Sample Integration Test', () => {
let connection: Connection
beforeAll(async (done) => {
setConnectionOptions({
type: 'sqlite',
database: ':memory:',
entities: ['sample/entities/**/*{.ts,.js}'],
})
connection = await useRefreshDatabase()
await useSeeding()
done()
})
let dataSource: DataSource

afterAll(async (done) => {
afterEach(async () => {
await tearDownDatabase()
})

test('Should create a user with the entity factory', async (done) => {
test('Should create a user with the entity factory', async () => {
setConnectionOptions(inMemoryDb)
dataSource = await useRefreshDatabase()
await useSeeding()

const createdUser = await factory(User)().create()
const user = await connection.getRepository(User).findOne(createdUser.id)
const user = await dataSource.getRepository(User).findOne({ where: { id: createdUser.id } })
expect(createdUser.firstName).toBe(user.firstName)
done()
})

test('Should be able to load a datasource.ts file', async () => {
setConnectionOptions({})
configureConnection({
dataSourcePath: join(__dirname, 'datasource.ts'),
})

dataSource = await useRefreshDatabase()
expect(dataSource.options).toEqual(
expect.objectContaining({
database: ':memory:',
entities: ['sample/entities/**/*{.ts,.js}'],
name: 'file',
type: 'sqlite',
}),
)
})
})
31 changes: 9 additions & 22 deletions src/commands/config.command.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,18 @@
import * as yargs from 'yargs'
import * as chalk from 'chalk'
import { printError } from '../utils/log.util'
import { configureConnection, getConnectionOptions } from '../connection'
import { configureConnection, loadDataSource } from '../connection'

export class ConfigCommand implements yargs.CommandModule {
command = 'config'
describe = 'Show the TypeORM config'

builder(args: yargs.Argv) {
return args
.option('n', {
alias: 'configName',
default: '',
describe: 'Name of the typeorm config file (json or js).',
})
.option('c', {
alias: 'connection',
default: '',
describe: 'Name of the typeorm connection',
})
.option('r', {
alias: 'root',
default: process.cwd(),
describe: 'Path to your typeorm config file',
})
return args.option('d', {
alias: 'dataSource',
demandOption: true,
describe: 'Path to the file where your DataSource instance is defined.',
})
}

async handler(args: yargs.Arguments) {
Expand All @@ -32,12 +21,10 @@ export class ConfigCommand implements yargs.CommandModule {
log('🌱 ' + chalk.bold(`TypeORM Seeding v${(pkg as any).version}`))
try {
configureConnection({
root: args.root as string,
configName: args.configName as string,
connection: args.connection as string,
dataSourcePath: args.dataSource as string,
})
const option = await getConnectionOptions()
log(option)
const ds = await loadDataSource()
log(ds.options)
} catch (error) {
printError('Could not find the orm config file', error)
process.exit(1)
Expand Down
113 changes: 52 additions & 61 deletions src/commands/seed.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,19 @@ import * as chalk from 'chalk'
import { importSeed } from '../importer'
import { loadFiles, importFiles } from '../utils/file.util'
import { runSeeder } from '../typeorm-seeding'
import { configureConnection, getConnectionOptions, ConnectionOptions, createConnection } from '../connection'
import { DataSource } from 'typeorm'
import { configureConnection, getConnectionOptions, ConnectionOptions, loadDataSource } from '../connection'

export class SeedCommand implements yargs.CommandModule {
command = 'seed'
describe = 'Runs the seeds'

builder(args: yargs.Argv) {
return args
.option('n', {
alias: 'configName',
default: '',
describe: 'Name of the typeorm config file (json or js).',
})
.option('c', {
alias: 'connection',
default: '',
describe: 'Name of the typeorm connection',
})
.option('r', {
alias: 'root',
default: process.cwd(),
describe: 'Path to your typeorm config file',
.option('d', {
alias: 'dataSource',
demandOption: true,
describe: 'Path to the file where your DataSource instance is defined.',
})
.option('seed', {
alias: 's',
Expand All @@ -39,67 +30,67 @@ export class SeedCommand implements yargs.CommandModule {
log('🌱 ' + chalk.bold(`TypeORM Seeding v${(pkg as any).version}`))
const spinner = ora('Loading ormconfig').start()
const configureOption = {
root: args.root as string,
configName: args.configName as string,
connection: args.connection as string,
dataSourcePath: args.dataSource as string,
}

let dataSource: DataSource | null = null
// Get TypeORM config file
let option: ConnectionOptions
try {
configureConnection(configureOption)
option = await getConnectionOptions()
dataSource = await loadDataSource()
spinner.succeed('ORM Config loaded')
} catch (error) {
panic(spinner, error, 'Could not load the config file!')
}

// Find all factories and seed with help of the config
spinner.start('Import Factories')
const factoryFiles = loadFiles(option.factories)
try {
await importFiles(factoryFiles)
spinner.succeed('Factories are imported')
} catch (error) {
panic(spinner, error, 'Could not import factories!')
}

// Show seeds in the console
spinner.start('Importing Seeders')
const seedFiles = loadFiles(option.seeds)
let seedFileObjects: any[] = []
try {
seedFileObjects = await Promise.all(seedFiles.map((seedFile) => importSeed(seedFile)))
seedFileObjects = seedFileObjects.filter(
(seedFileObject) => args.seed === undefined || args.seed === seedFileObject.name,
)
spinner.succeed('Seeders are imported')
} catch (error) {
panic(spinner, error, 'Could not import seeders!')
}
// Find all factories and seed with help of the config
spinner.start('Import Factories')
const factoryFiles = loadFiles(option.factories)
try {
await importFiles(factoryFiles)
spinner.succeed('Factories are imported')
} catch (error) {
panic(spinner, error, 'Could not import factories!')
}

// Get database connection and pass it to the seeder
spinner.start('Connecting to the database')
try {
await createConnection()
spinner.succeed('Database connected')
} catch (error) {
panic(spinner, error, 'Database connection failed! Check your typeORM config file.')
}
// Show seeds in the console
spinner.start('Importing Seeders')
const seedFiles = loadFiles(option.seeds)
let seedFileObjects: any[] = []
try {
seedFileObjects = await Promise.all(seedFiles.map((seedFile) => importSeed(seedFile)))
seedFileObjects = seedFileObjects.filter(
(seedFileObject) => args.seed === undefined || args.seed === seedFileObject.name,
)
spinner.succeed('Seeders are imported')
} catch (error) {
panic(spinner, error, 'Could not import seeders!')
}

// Run seeds
for (const seedFileObject of seedFileObjects) {
spinner.start(`Executing ${seedFileObject.name} Seeder`)
// Get database connection and pass it to the seeder
spinner.start('Connecting to the database')
try {
await runSeeder(seedFileObject)
spinner.succeed(`Seeder ${seedFileObject.name} executed`)
await loadDataSource()
spinner.succeed('Database connected')
} catch (error) {
panic(spinner, error, `Could not run the seed ${seedFileObject.name}!`)
panic(spinner, error, 'Database connection failed! Check your typeORM config file.')
}

// Run seeds
for (const seedFileObject of seedFileObjects) {
spinner.start(`Executing ${seedFileObject.name} Seeder`)
try {
await runSeeder(seedFileObject)
spinner.succeed(`Seeder ${seedFileObject.name} executed`)
} catch (error) {
panic(spinner, error, `Could not run the seed ${seedFileObject.name}!`)
}
}
}

log('👍 ', chalk.gray.underline(`Finished Seeding`))
process.exit(0)
log('👍 ', chalk.gray.underline(`Finished Seeding`))
process.exit(0)
} catch (error) {
panic(spinner, error, 'Could not load the config file!')
}
}
}

Expand Down
Loading