import { Controller, Get, HttpException, HttpService, HttpStatus, Logger, Param, Query } from '@nestjs/common'; import { Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { ApiQuery } from '@nestjs/swagger'; import { Post } from './schemas/post.schema'; import { PostsService } from './posts.service'; import { Tag } from './schemas/tag.schema'; import { PostWithMeta } from './schemas/postWithMeta.schema'; @Controller('posts') export class PostsController { private readonly logger = new Logger(PostsController.name); constructor(private readonly httpService: HttpService, private readonly postsService: PostsService) {} @Get() @ApiQuery({ name: 'include', type: String, required: false }) @ApiQuery({ name: 'fields', type: String, required: false }) @ApiQuery({ name: 'formats', type: String, required: false }) @ApiQuery({ name: 'filter', type: String, required: false }) @ApiQuery({ name: 'limit', type: String, required: false }) @ApiQuery({ name: 'page', type: String, required: false }) @ApiQuery({ name: 'order', type: String, required: false }) public async findAll(@Query() query): Promise<PostWithMeta> { const result = this.httpService .get(`${process.env.GHOST_HOST_AND_PORT}/ghost/api/v3/content/posts`, { params: { key: process.env.GHOST_CONTENT_API_KEY, include: query.include ? query.include : null, fields: query.fields ? query.fields : null, formats: query.formats ? query.formats : null, filter: query.filter ? query.filter : null, limit: query.limit ? query.limit : null, order: query.order ? query.order : null, page: query.page ? query.page : null, }, }) .pipe( map((response) => response.data), catchError((err) => { this.logger.error(err); throw new HttpException('Invalid ghost configuration', HttpStatus.BAD_REQUEST); }) ); return new Promise((resolve) => { result.subscribe((postData: PostWithMeta) => { postData.posts.forEach((post: Post) => { return this.postsService.formatPosts(post); }); resolve(postData); }); }); } @Get('tags') public async findAllTags(): Promise<{ public: Tag[]; commune: Tag[]; others: Tag[] }> { return Promise.all([ this.postsService.getLocationTags(), this.postsService.getPublicTags(), this.postsService.getRegularTags(), ]).then((data) => { return { commune: data[0], public: data[1], others: data[2] }; }); } @Get(':id') public async getPostbyId(@Param('id') id: string): Promise<Observable<{ posts: Post[] }>> { return this.httpService .get(`${process.env.GHOST_HOST_AND_PORT}/ghost/api/v3/content/posts/` + id, { params: { key: process.env.GHOST_CONTENT_API_KEY, include: 'tags,authors', }, }) .pipe( map((response) => { return { posts: [this.postsService.formatPosts(response.data.posts[0])] }; }) ); } }