07 Seed - jp7io/typescript-crud-api GitHub Wiki

Seed

Create script

mkdir ./src/utils
code ./src/utils/seed.ts
import { createConnection, getRepository } from 'typeorm';
import { Author } from '../entity/Author';
import seed from './seed.json';

createConnection()
  .then(async () => {
    const authorRepository = getRepository(Author);

    seed.authors.map(async (author) => await authorRepository.save(author));
  })
  .catch((error) => console.log(error));

Sample data

code ./src/utils/seed.json
{
  "authors": [
    {
      "name": "Why The Lucky Stiff",
      "articles": [
        {
          "title": "Create Things",
          "text":
            "When you don't create things, you become defined by your tastes rather than ability. Your tastes only narrow and exclude people. So create."
        }
      ]
    },
    {
      "name": "Martin Fowler",
      "articles": [
        {
          "title": "Code for Humans",
          "text":
            "Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
        }
      ]
    },
    {
      "name": "John Woods",
      "articles": [
        {
          "title": "Be Aware",
          "text":
            "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
        }
      ]
    }
  ]
}

Add script shortcut

code ./package.json
{
  ...
  "scripts": {
    ...
    "seed": "tsc;node ./build/utils/seed.js",
    "test": ...
  },
  ...
}

Test

# postgres
dropdb typescript-crud
createdb typescript-crud
yarn seed
yarn dev
curl "http://localhost:4000/authors?relations[]=articles"
# [{"id":1,"name":"Why The Lucky Stiff","articles":[{"id":3,"title":"Create Things","text":"When..."}]},{"id":2,"name":"John Woods","articles":[{"id":2,"title":"Be Aware","text":"Always..."}]},{"id":1,"name":"Martin Fowler","articles":[{"id":1,"title":"Code for Humans","text":"Any..."}]}]

Commit

git add .
git commit -m "Seed"

Next step: Documentation