04 Associations - jp7io/typescript-crud-api GitHub Wiki

Associations

Create entity for Author

code ./src/entity/Author.ts
import { Entity, Column, OneToMany } from 'typeorm';
import { Record } from './Record';
import { Article } from './Article';

@Entity()
export class Author extends Record {
  @Column()
  name: string;

  @OneToMany((type) => Article, (article) => article.author, {
    cascade: ['insert', 'update'],
  })
  articles: Article[];
}

Include Author association in Article entity

code ./src/entity/Article.ts
import { ..., ManyToOne } from 'typeorm';
...
import { Author } from './Author';

@Entity()
export class Article extends Record {
  ...

  @ManyToOne((type) => Author, (author) => author.articles, {
    onDelete: 'CASCADE',
  })
  author: Author;
}

Create authors router

code ./src/routes/authors.ts
import { Router } from 'express';
import { authorsController } from '../controllers/authors';

export const authorsRoutes = (router: Router) => {
  const { findAll, findOne, create, update, remove } = authorsController();

  router.get('/authors', findAll);
  router.get('/authors/:id', findOne);
  router.post('/authors', create);
  router.put('/authors/:id', update);
  router.delete('/authors/:id', remove);

  return router;
};

Create authors controller

code ./src/controllers/authors.ts
import { getRepository } from 'typeorm';
import { Author } from '../entity/Author';
import { recordsController } from './records';

export const authorsController = () => {
  const repository = getRepository(Author);

  return recordsController<Author>(repository);
};

Allow relations in records controller

code ./src/controllers/records.ts
  ...
  const findAll = async (...) => {
    ...
    const results = await repository.find(req.query);
    ...
  });

  const findOne = async (...) => {
    ...
    const results = await repository.findOne(..., req.query);
    ...
  });
  ...

Add authors routes to Express

code ./src/app.ts
...
import { articlesRoutes } from './routes/articles';
import { authorsRoutes } from './routes/authors';

  ...
  app.use(articlesRoutes(router));
  app.use(authorsRoutes(router));
  ...

Test application

yarn dev
curl -X POST  -H "Content-Type: application/json" \
-d '{"name":"Author Name"}' \
http://localhost:4000/authors
# {"name":"Author Name","id":1}
curl -X POST  -H "Content-Type: application/json" \
-d '{"title":"Article With Author", "text":"Article Text", "author":1}' \
http://localhost:4000/articles
# {"title":"Article With Author","text":"Article Text","author":1,"id":2}
curl "http://localhost:4000/articles?relations[]=author"
# [{...},{"id":2,"title":"Article With Author","text":"Article Text","author":{"id":1,"name":"Author Name"}}]

Commit

git add .
git commit -m "Associations"

Next step: Validations

⚠️ **GitHub.com Fallback** ⚠️