Skip to content

Instantly share code, notes, and snippets.

@nicobytes
Last active September 5, 2021 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicobytes/68163c6413e75445db04149ff1ffad3a to your computer and use it in GitHub Desktop.
Save nicobytes/68163c6413e75445db04149ff1ffad3a to your computer and use it in GitHub Desktop.

1 Entity

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

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

  @Column()
  url: string;
}

// src/tasks/tasks.module.ts
import { Photo } from './entities/photo.entity';

2 Relations

// src/tasks/entities/profile.entity.ts
@OneToMany(() => Photo, (photo) => photo.profile)
photos: Photo[];

// src/tasks/entities/photo.entity.ts
@ManyToOne(() => Profile, (profile) => profile.photos)
@JoinColumn({ name: 'profile_id' })
profile: Profile;

3 Migrations

npm run migrations:generate -- add-photos
npm run migrations:run

4 Create service and controllers

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

5 addPhoto

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Photo } from './../entities/photo.entity';
import { Profile } from './../entities/profile.entity';

@Injectable()
export class PhotosService {
  constructor(
    @InjectRepository(Photo) private photoRepo: Repository<Photo>,
    @InjectRepository(Profile) private profileRepo: Repository<Profile>,
  ) {}

  async addPhoto(data: any) {
    const profile = await this.profileRepo.findOne(data.profileId);
    const newPhoto = new Photo();
    newPhoto.url = data.url;
    newPhoto.profile = profile;
    return this.photoRepo.save(newPhoto);
  }
}

5 Controller

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

import { PhotosService } from './../services/photos.service';

@Controller('photos')
export class PhotosController {
  constructor(private photosService: PhotosService) {}

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

6 User service

  findAll() {
    return this.usersRepo.find({
      relations: ['profile', 'profile.photos'],
    });
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment