Skip to content
Snippets Groups Projects
posts.controller.ts 2.76 KiB
import { Controller, Get, HttpService, 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 {
  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 = await 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) => {
          Logger.error(err);
          return new Observable();
        })
      );
    return new Promise((resolve) => {
      result.subscribe((result: PostWithMeta) => {
        result.posts.map((post: Post) => (!post.custom_excerpt ? (post.excerpt = 'Inconnu') : ''));
        resolve(result);
      });
    });
  }

  @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) => response.data));
  }
}