Skip to content

Instantly share code, notes, and snippets.

@nicobytes
Last active October 13, 2021 19:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicobytes/b1041cab6cbda2bd88a686e11f4927c5 to your computer and use it in GitHub Desktop.
Save nicobytes/b1041cab6cbda2bd88a686e11f4927c5 to your computer and use it in GitHub Desktop.

1 Entity

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class Category {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

// src/tasks/tasks.module.ts
import { Category } from './entities/category.entity';

2 Relations

// src/tasks/entities/task.entity.ts
@ManyToMany(() => Category)
@JoinTable()
categories: Category[];


// src/tasks/entities/category.entity.ts
@ManyToMany(() => Task, (task) => task.categories)
tasks: Task[];

// src/tasks/entities/task.entity.ts
@ManyToMany(() => Category, (category) => category.tasks)
@JoinTable({
name: 'tasks_categories',
joinColumn: {
  name: 'task_id',
},
inverseJoinColumn: {
  name: 'category_id',
},
})
categories: Category[];

3 Migrations

npm run migrations:generate -- categories
npm run migrations:run

4 Create service and controllers

nest g service tasks/services/categories --flat
nest g co tasks/controllers/categories --flat

5 addCategory

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Category } from './../entities/category.entity';

@Injectable()
export class CategoriesService {
  constructor(
    @InjectRepository(Category) private categoryRepo: Repository<Category>,
  ) {}

  create(body: any) {
    const category = this.categoryRepo.create(body);
    return this.categoryRepo.save(category);
  }
}

6 Controller

import { Controller, Post, Body } from '@nestjs/common';

import { CategoriesService } from './../services/categories.service';

@Controller('categories')
export class CategoriesController {
  constructor(private categoriesService: CategoriesService) {}

  @Post()
  addPhoto(@Body() body: any) {
    return this.categoriesService.create(body);
  }
}

7 add task

@InjectRepository(Category) private categoryRepo: Repository<Category>,

async create(body: any) {
    const newTask = new Task();
    newTask.name = body.name;
    const categories = await this.categoryRepo.findByIds(body.categoriesIds);
    newTask.categories = categories;
    return this.tasksRepo.save(newTask);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment