import { Injectable } from '@nestjs/common' ; import { InjectConnection } from '@nestjs/typeorm' ; import * as _ from 'lodash' ; import { Connection , In } from 'typeorm' ; import { ID } from '../../common/shared-types' ; import { formatOneMeta } from '../../common/utils' ; import { Post as PostEntity , PostMeta } from '../../entity' ; @ Injectable ( ) export class AttachmentService { constructor ( @ InjectConnection ( ) private connection ) { } param id async findById ( id ) { return await this . connection . getRepository ( PostEntity ) . findOne ( { id , } ) ; } async getFormatData ( item ) { switch ( item . type ) { case 'post-format-audio' : { if ( ! _ . isEmpty ( item . block ) ) { const postId = JSON . parse ( item . block ) [ 0 ] ; const block = await this . getAttachmentInfo ( postId ) ; if ( ! Object . is ( block . meta . _attachment_file , undefined ) ) { item . guid = block . meta . _attachment_file ; } if ( ! Object . is ( block . meta . _attachment_metadata , undefined ) ) { if ( block . meta . _attachment_metadata !== '{}' ) { item = _ . extend ( item , block . meta . _attachment_metadata ) ; } } } Reflect . deleteProperty ( item , 'meta' ) ; break ; } default : break ; } return item ; } param id private async getAttachmentInfo ( id ) { const data = await this . findById ( id ) ; return formatOneMeta ( data ) ; } param ids private async getAudios ( ids ) { this . connection . manager . createQueryBuilder ( PostEntity , 'post' ) . orderBy ( `INSTR (',${ ids },', CONCAT(',',id,','))` ) ; } param type param postId async getAttachment ( postId , type = 'file' ) { let where = { postId , } ; switch ( type ) { case 'file' : { where = _ . extend ( { key : '_attachment_file' } , where ) ; const attachment = await this . connection . manager . createQueryBuilder ( ) . select ( ) . from ( PostMeta , 'pm' ) . where ( `pm.key = :key AND pm.postId = :postId` , { key : '_attachment_file' , postId } ) . getRawOne ( ) ; if ( ! _ . isEmpty ( attachment ) ) { return JSON . parse ( attachment . value ) ; } break ; } case 'meta' : break ; } } param ids async getAttachments ( ids ) { let where = { postId : In ( ids ) , } ; where = _ . extend ( { key : '_attachment_file' } , where ) ; const list = await this . connection . getRepository ( PostMeta ) . find ( { where , } ) ; return list ; } }