import { BadRequestException , Injectable , NotFoundException , } from '@nestjs/common' ; import { load } from 'js-yaml' ; import { InjectModel } from 'nestjs-typegoose' ; import { SnippetModel , SnippetType } from './snippet.model' ; @ Injectable ( ) export class SnippetService { constructor ( @ InjectModel ( SnippetModel ) private readonly snippetModel ) { } get model ( ) { return this . snippetModel ; } async create ( model ) { const isExist = await this . model . countDocuments ( { name : model . name , reference : model . reference || 'root' , } ) ; if ( isExist ) { throw new BadRequestException ( 'snippet is exist' ) ; } await this . validateType ( model ) ; return await this . model . create ( { ... model , created : new Date ( ) } ) ; } async update ( id , model ) { await this . validateType ( model ) ; delete model . created ; return await this . model . findByIdAndUpdate ( id , { ... model } , { new : true } ) ; } async delete ( id ) { await this . model . deleteOne ( { _id : id } ) ; } private async validateType ( model ) { switch ( model . type ) { case SnippetType . JSON : { try { JSON . parse ( model . raw ) ; } catch { throw new BadRequestException ( 'content is not valid json' ) ; } break ; } case SnippetType . YAML : { try { load ( model . raw ) ; } catch { throw new BadRequestException ( 'content is not valid yaml' ) ; } break ; } case SnippetType . Function : throw new BadRequestException ( 'Serverless functions are not currently supported' ) ; case SnippetType . Text : default : { break ; } } } async getSnippetById ( id ) { const doc = await this . model . findById ( id ) . lean ( ) ; return this . attachSnippet ( doc ) ; } param name param reference returns async getSnippetByName ( name , reference ) { const doc = await this . model . findOne ( { name , reference } ) . lean ( ) ; return this . attachSnippet ( doc ) ; } async attachSnippet ( model ) { if ( ! model ) { throw new NotFoundException ( ) ; } switch ( model . type ) { case SnippetType . JSON : { Reflect . set ( model , 'data' , JSON . parse ( model . raw ) ) ; break ; } case SnippetType . YAML : { Reflect . set ( model , 'data' , load ( model . raw ) ) ; break ; } case SnippetType . Text : { Reflect . set ( model , 'data' , model . raw ) ; break ; } } return model as SnippetModel & { data : any ; } ; } }