/
post.repository.ts
194 lines (164 loc) · 6.62 KB
/
post.repository.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import { TDeleteManyInput, TPagedList, TPagedParams, TPost, TPostFilter, TPostInput } from '@cromwell/core';
import readingTime from 'reading-time';
import sanitizeHtml from 'sanitize-html';
import { Brackets, EntityRepository, getCustomRepository, SelectQueryBuilder } from 'typeorm';
import { checkEntitySlug, getPaged, handleBaseInput, handleCustomMetaInput } from '../helpers/base-queries';
import { getLogger } from '../helpers/logger';
import { Post } from '../models/entities/post.entity';
import { Tag } from '../models/entities/tag.entity';
import { PostFilterInput } from '../models/filters/post.filter';
import { PagedParamsInput } from '../models/inputs/paged-params.input';
import { BaseRepository } from './base.repository';
import { TagRepository } from './tag.repository';
import { UserRepository } from './user.repository';
const logger = getLogger();
@EntityRepository(Post)
export class PostRepository extends BaseRepository<Post> {
constructor() {
super(Post);
}
async getPosts(params?: TPagedParams<TPost>): Promise<TPagedList<Post>> {
return this.getPaged(params);
}
async getPostById(id: number): Promise<Post> {
return this.getById(id);
}
async getPostBySlug(slug: string): Promise<Post> {
return this.getBySlug(slug);
}
private async handleBasePostInput(post: Post, input: TPostInput, action: 'update' | 'create') {
const author =
input.authorId &&
(await getCustomRepository(UserRepository)
.getUserById(input.authorId)
.catch(() => null));
await handleBaseInput(post, input);
if (input.tagIds) {
const tags = await getCustomRepository(TagRepository).getTagsByIds(input.tagIds);
post.tags = tags;
}
if (input.readTime) {
post.readTime = input.readTime;
} else if (input.content) {
const text = sanitizeHtml(input.content ?? '', {
allowedTags: [],
});
post.readTime = readingTime(text).minutes + '';
}
post.title = input.title;
post.mainImage = input.mainImage ?? null;
post.content = input.content
? sanitizeHtml(input.content, {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'iframe']),
allowedAttributes: {
a: ['href', 'name', 'target'],
'*': ['href', 'class', 'src', 'align', 'alt', 'title', 'width', 'height', 'style'],
},
})
: input.content;
post.delta = input.delta;
post.excerpt = input.excerpt;
post.published = input.published;
post.featured = input.featured;
post.authorId = input.authorId;
if (author) post.author = author;
post.publishDate = input.publishDate;
if (action === 'create') await post.save();
await checkEntitySlug(post, Post);
await handleCustomMetaInput(post, input);
}
async createPost(createPost: TPostInput, id?: number | null): Promise<Post> {
const post = new Post();
if (id) post.id = id;
await this.handleBasePostInput(post, createPost, 'create');
await this.save(post);
return post;
}
async updatePost(id: number, updatePost: TPostInput): Promise<Post> {
const post = await this.getById(id);
await this.handleBasePostInput(post, updatePost, 'update');
await this.save(post);
return post;
}
async deletePost(id: number): Promise<boolean> {
const post = await this.getPostById(id);
if (!post) {
logger.error('PostRepository::deletePost failed to find post by id');
return false;
}
const res = await this.delete(id);
return true;
}
applyPostFilter(qb: SelectQueryBuilder<TPost>, filterParams?: TPostFilter) {
this.applyBaseFilter(qb, filterParams);
if (filterParams?.tagIds && filterParams.tagIds.length > 0) {
qb.leftJoin(`${this.metadata.tablePath}.tags`, getCustomRepository(TagRepository).metadata.tablePath);
qb.andWhere(`${getCustomRepository(TagRepository).metadata.tablePath}.id IN (:...ids)`, {
ids: filterParams.tagIds,
});
}
// Search by title
if (filterParams?.titleSearch) {
const titleSearch = `%${filterParams.titleSearch}%`;
const query = `${this.metadata.tablePath}.title ${this.getSqlLike()} :titleSearch`;
qb.andWhere(query, { titleSearch });
}
if (filterParams?.authorId) {
const authorId = filterParams.authorId;
const query = `${this.metadata.tablePath}.${this.quote('authorId')} = :authorId`;
qb.andWhere(query, { authorId });
}
// Filter by published
if (filterParams?.published !== undefined && filterParams?.published !== null) {
if (filterParams.published === true) {
qb.andWhere(`${this.metadata.tablePath}.published = ${this.getSqlBoolStr(true)}`);
}
if (filterParams.published === false) {
const brackets = new Brackets((subQb) => {
subQb.where(`${this.metadata.tablePath}.published = ${this.getSqlBoolStr(false)}`);
subQb.orWhere(`${this.metadata.tablePath}.published IS NULL`);
});
qb.andWhere(brackets);
}
}
// Filter by featured
if (filterParams?.featured !== undefined && filterParams?.featured !== null) {
if (filterParams.featured === true) {
qb.andWhere(`${this.metadata.tablePath}.featured = ${this.getSqlBoolStr(true)}`);
}
if (filterParams.featured === false) {
const brackets = new Brackets((subQb) => {
subQb.where(`${this.metadata.tablePath}.featured = ${this.getSqlBoolStr(false)}`);
subQb.orWhere(`${this.metadata.tablePath}.featured IS NULL`);
});
qb.andWhere(brackets);
}
}
return qb;
}
async getFilteredPosts(pagedParams?: TPagedParams<TPost>, filterParams?: TPostFilter): Promise<TPagedList<TPost>> {
const qb = this.createQueryBuilder(this.metadata.tablePath);
qb.select();
this.applyPostFilter(qb, filterParams);
return await getPaged(qb, this.metadata.tablePath, pagedParams);
}
async deleteManyFilteredPosts(input: TDeleteManyInput, filterParams?: TPostFilter): Promise<boolean> {
if (!filterParams) return this.deleteMany(input);
const qbSelect = this.createQueryBuilder(this.metadata.tablePath).select([`${this.metadata.tablePath}.id`]);
this.applyPostFilter(qbSelect, filterParams);
this.applyDeleteMany(qbSelect, input);
const qbDelete = this.createQueryBuilder(this.metadata.tablePath)
.delete()
.where(`${this.metadata.tablePath}.id IN (${qbSelect.getQuery()})`)
.setParameters(qbSelect.getParameters());
await qbDelete.execute();
return true;
}
async getTagsOfPost(postId: number): Promise<Tag[] | undefined | null> {
return (
await this.findOne(postId, {
relations: ['tags'],
})
)?.tags;
}
}