Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
2.1 kB
1
Indexable
Never
import { postInput } from './post.input';
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { CreatePostDto } from './post.dto';
import { PostsService } from './posts.service';
import { createWriteStream, ReadStream } from 'fs';
import { FileUpload } from 'graphql-upload';

@Resolver()
export class PostsResolver {
  constructor(private readonly postsService: PostsService) {}

  private async writeFile(
    stream: ReadStream,
    filename: string
  ): Promise<boolean> {
    return new Promise((resolve, reject) => {
      stream
        .pipe(createWriteStream(`${process.cwd()}/src/posts/uploads/${filename}`))
        .on('finish', () => resolve(true))
        .on('error', (err) => reject(err));
    });
  }

  private async createFile (arr: FileUpload[]): Promise<string[]> {
    let stringArr: string[] = [];
      await Promise.all(
        arr.map(async (file: FileUpload): Promise<void> => {
          file = await file;
          let fileExtension = file.filename.split('.').pop();
          let temp = file.filename.split('.')
          let fileName = temp.splice(0, temp.length - 1).join('') + '-' + Date.now() + '-' + '.' + fileExtension
          this.writeFile(file.createReadStream(), `${fileName}`);
          stringArr.push(fileName)
        })
      )
      return stringArr
  }

  @Query(() => String)
  async hello () {
    return 'Hello'
  }

  @Query(() => [CreatePostDto])
  async posts () {
    return this.postsService.findAll()
  }

  @Mutation(() => Boolean )
  async createPost (@Args('input') input: postInput) {
    let images: FileUpload[] | String[] = input.images
    let posters: FileUpload[] | String[] = input.posters
    delete input.images
    delete input.posters
    Promise.all([
      this.createFile(images),
      this.createFile(posters)
    ]).then((values) => { 
        images = values[0],
        posters = values[1] 
      }).then(() => {
          let data = input
          data.images = images
          this.postsService.create
        })
  }
 
}