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

Does not create any data in db #110

Open
Gasorey opened this issue Jan 12, 2021 · 5 comments
Open

Does not create any data in db #110

Gasorey opened this issue Jan 12, 2021 · 5 comments

Comments

@Gasorey
Copy link

Gasorey commented Jan 12, 2021

I'm trying to use it to populate a postgres DB but it does not work.

here's my script:

"seed:config": "ts-node -r tsconfig-paths/register ./node_modules/typeorm-seeding/dist/cli.js config",
"seed:run": "ts-node ./node_modules/typeorm-seeding/dist/cli.js seed",

My ormconfig.json:

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "quero",
  "password": "docker",
  "database": "quero",
  "entities": ["./src/modules/university/infra/typeorm/entities/*.ts"],
  "seeds": ["src/modules/university/infra/seeds/*.ts"],
  "factories": ["src/modules/university/infra/factory/*.ts"],
  "migrations": ["./src/shared/infra/typeorm/migrations/*.ts"],
  "cli": {
    "migrationsDir": "./src/shared/infra/typeorm/migrations/"
  },
  "logging": ["error"]
}

My factor and my seed:

import Faker from 'faker';
import { define } from 'typeorm-seeding';
import University from '../entities/University';

define(University, (faker: typeof Faker) => {
  const name = faker.company.companyName();
  const score = faker.random.float(10);
  const logo_number = faker.random.number(100);

  const university = new University();

  university.name = name;
  university.score = score;
  university.logo_url = `https://www.s3.someamazonS3.com/someBucket/somePath/${logo_number}.png`;
  university.create_at = new Date();
  return university;
});

Seed:

import { Factory, Seeder } from 'typeorm-seeding';
import University from '../entities/University';
import { Connection } from 'typeorm';
import Faker from 'faker';

const faker = Faker;
export default class CreateUniversity implements Seeder {
  public async run(factory: Factory): Promise<void> {
    await factory(University)().createMany(10);
  }
}

When i run seed:run it works doenst show me any error but dont create any data on db

@dmitrif
Copy link

dmitrif commented Jan 24, 2021

Try updating ormconfig.json to ormconfig.js with:

import path from 'path';

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "quero",
  "password": "docker",
  "database": "quero",
  "entities": [path.join(__dirname, "./src/modules/university/infra/typeorm/entities/*.ts")],
  "seeds": [path.join(__dirname, ".src/modules/university/infra/seeds/*.ts")],
  "factories": [path.join(__dirname, "src/modules/university/infra/factory/*.ts")],
  "migrations": ["./src/shared/infra/typeorm/migrations/*.ts"],
  "cli": {
    "migrationsDir": "./src/shared/infra/typeorm/migrations/"
  },
  "logging": ["error"]
}

@metalcamp
Copy link
Collaborator

You can also use .env. Make sure you list paths to dist/build folder.

@quangdvn
Copy link

I'm trying to use it to populate a postgres DB but it does not work.

here's my script:

"seed:config": "ts-node -r tsconfig-paths/register ./node_modules/typeorm-seeding/dist/cli.js config",
"seed:run": "ts-node ./node_modules/typeorm-seeding/dist/cli.js seed",

My ormconfig.json:

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "quero",
  "password": "docker",
  "database": "quero",
  "entities": ["./src/modules/university/infra/typeorm/entities/*.ts"],
  "seeds": ["src/modules/university/infra/seeds/*.ts"],
  "factories": ["src/modules/university/infra/factory/*.ts"],
  "migrations": ["./src/shared/infra/typeorm/migrations/*.ts"],
  "cli": {
    "migrationsDir": "./src/shared/infra/typeorm/migrations/"
  },
  "logging": ["error"]
}

My factor and my seed:

import Faker from 'faker';
import { define } from 'typeorm-seeding';
import University from '../entities/University';

define(University, (faker: typeof Faker) => {
  const name = faker.company.companyName();
  const score = faker.random.float(10);
  const logo_number = faker.random.number(100);

  const university = new University();

  university.name = name;
  university.score = score;
  university.logo_url = `https://www.s3.someamazonS3.com/someBucket/somePath/${logo_number}.png`;
  university.create_at = new Date();
  return university;
});

Seed:

import { Factory, Seeder } from 'typeorm-seeding';
import University from '../entities/University';
import { Connection } from 'typeorm';
import Faker from 'faker';

const faker = Faker;
export default class CreateUniversity implements Seeder {
  public async run(factory: Factory): Promise<void> {
    await factory(University)().createMany(10);
  }
}

When i run seed:run it works doenst show me any error but dont create any data on db

I am running into the same issue as you, have you solved it yet ?

@dmitrif
Copy link

dmitrif commented Mar 31, 2021

@quangdvn Hi, have you tried my approach above?

@Gasorey
Copy link
Author

Gasorey commented Mar 31, 2021

I didnt solve this issue, just gave up cuz i had to complete the tech test.

To create sees i just create a new migration:

export class SeedMigrations1610485872039 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.manager
      .createQueryBuilder()
      .insert()
      .into('university')
      .values(fakeUniversities)
      .execute();

    await queryRunner.manager
      .createQueryBuilder()
      .insert()
      .into('campus')
      .values(fakeCampus)
      .execute();

    await queryRunner.manager
      .createQueryBuilder()
      .insert()
      .into('course')
      .values(fakeCourse)
      .execute();

    await queryRunner.manager
      .createQueryBuilder()
      .insert()
      .into('sales')
      .values(fakeSales)
      .execute();
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.clearTable('sales');
    await queryRunner.clearTable('course');
    await queryRunner.clearTable('campus');
    await queryRunner.clearTable('university');
  }
}

and the fake values come from this:

const fakeUniversities = [...Array(100)].map(university => ({
  name: Faker.company.companyName(),
  score: Faker.random.float({
    max: 10,
    min: 0,
  }),
  logo_url: Faker.image.imageUrl(),
}));

const fakeCampus = [...Array(100)].map(campus => ({
  name: Faker.address.state(),
  city: Faker.address.streetName(),
  university_id: getRandomNumber(1, 100).toFixed(0),
}));

const fakeCourse = [...Array(100)].map(course => ({
  name: Faker.name.jobArea(),
  kind: Faker.random.arrayElement(['Presencial', 'EaD', 'Hibrido']),
  level: Faker.random.arrayElement([
    'Tecnólogo',
    'Bacharelado',
    'Licenciatura',
  ]),
  shift: Faker.random.arrayElement(['Virtual', 'Manhã', 'Noite', 'Integral']),
  university_id: getRandomNumber(1, 100).toFixed(0),
  campus_id: getRandomNumber(1, 100).toFixed(0),
}));

const fakeSales = [...Array(100)].map(sale => {
  const full_price = Faker.random.number({
    min: 800,
    max: 5000,
    precision: 2,
  });
  const year = getRandomNumber(2021, 2023).toFixed(0);
  const semester = Faker.random.arrayElement(['1', '2']);
  const discount = getRandomNumber(0.1, 99.9);
  const month =
    semester > '1'
      ? Faker.random.number({ min: 7, max: 12 })
      : Faker.random.number({ min: 1, max: 6 });
  const newSale = {
    full_price: full_price,
    price_with_discount: Number((full_price * (1 - discount / 100)).toFixed(2)),
    discount_percentage: discount,
    start_date: `${Faker.random.number({
      min: 1,
      max: 30,
    })}/${month}/${year}`,
    enrollment_semester: `${year}.${semester}`,
    enabled: Faker.random.boolean(),
    university_id: getRandomNumber(1, 100).toFixed(0),
    campus_id: getRandomNumber(1, 100).toFixed(0),
    course_id: getRandomNumber(1, 100).toFixed(0),
  };
  return newSale;
});

export { fakeCampus, fakeCourse, fakeSales, fakeUniversities };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants