|
| 1 | +import { ApolloError, AuthenticationError } from 'apollo-server-koa'; |
| 2 | +import { ApolloContext } from './../app'; |
| 3 | +import { getRepository } from 'typeorm'; |
| 4 | +import Post from '../entity/Post'; |
| 5 | +import PostHistory from '../entity/PostHistory'; |
| 6 | +import searchSync from '../search/searchSync'; |
| 7 | + |
| 8 | +const postHistoryService = { |
| 9 | + async createPostHistory(args: CreatePostHistoryArgs, ctx: ApolloContext) { |
| 10 | + if (!ctx.user_id) { |
| 11 | + throw new AuthenticationError('Not Logged In'); |
| 12 | + } |
| 13 | + |
| 14 | + // check ownPost |
| 15 | + const { post_id, title, body, is_markdown } = args; |
| 16 | + |
| 17 | + const postRepo = getRepository(Post); |
| 18 | + const post = await postRepo.findOne(post_id); |
| 19 | + |
| 20 | + if (!post) { |
| 21 | + throw new ApolloError('Post not found', 'NOT_FOUND'); |
| 22 | + } |
| 23 | + if (post.fk_user_id !== ctx.user_id) { |
| 24 | + throw new ApolloError('This post is not yours', 'NO_PERMISSION'); |
| 25 | + } |
| 26 | + |
| 27 | + // create postHistory |
| 28 | + const postHistoryRepo = getRepository(PostHistory); |
| 29 | + const postHistory = new PostHistory(); |
| 30 | + Object.assign(postHistory, { title, body, is_markdown, fk_post_id: post_id }); |
| 31 | + |
| 32 | + await postHistoryRepo.save(postHistory); |
| 33 | + |
| 34 | + const [data, count] = await postHistoryRepo.findAndCount({ |
| 35 | + where: { |
| 36 | + fk_post_id: post_id, |
| 37 | + }, |
| 38 | + order: { |
| 39 | + created_at: 'DESC', |
| 40 | + }, |
| 41 | + }); |
| 42 | + |
| 43 | + if (count > 10) { |
| 44 | + await postHistoryRepo |
| 45 | + .createQueryBuilder('post_history') |
| 46 | + .delete() |
| 47 | + .where('fk_post_id = :postId', { |
| 48 | + postId: post_id, |
| 49 | + }) |
| 50 | + .andWhere('created_at < :createdAt', { createdAt: data[9].created_at }) |
| 51 | + .execute(); |
| 52 | + |
| 53 | + setTimeout(() => { |
| 54 | + searchSync.update(post.id).catch(console.error); |
| 55 | + }, 0); |
| 56 | + } |
| 57 | + |
| 58 | + return postHistory; |
| 59 | + }, |
| 60 | +}; |
| 61 | + |
| 62 | +export type CreatePostHistoryArgs = { |
| 63 | + post_id: string; |
| 64 | + title: string; |
| 65 | + body: string; |
| 66 | + is_markdown: boolean; |
| 67 | +}; |
| 68 | + |
| 69 | +export default postHistoryService; |
0 commit comments