import { Provide, Scope, ScopeEnum } from '@midwayjs/core'; import { InjectEntityModel } from '@midwayjs/typeorm'; import { Repository, Like, In } from 'typeorm'; import { Site } from '../entity/site.entity'; import { WpSite } from '../interface'; import { UpdateSiteDTO } from '../dto/site.dto'; @Provide() @Scope(ScopeEnum.Singleton) export class SiteService { @InjectEntityModel(Site) siteModel: Repository; async syncFromConfig(sites: WpSite[] = []) { for (const s of sites) { const exist = await this.siteModel.findOne({ where: { siteName: s.siteName } }); const payload: Partial = { siteName: s.siteName, apiUrl: (s as any).wpApiUrl, consumerKey: (s as any).consumerKey, consumerSecret: (s as any).consumerSecret, type: 'woocommerce', }; if (exist) await this.siteModel.update({ id: exist.id }, payload); else await this.siteModel.insert(payload as Site); } } async create(data: Partial) { await this.siteModel.insert(data as Site); return true; } async update(id: string | number, data: UpdateSiteDTO) { const payload: Partial = { ...data, isDisabled: data.isDisabled === undefined ? undefined : data.isDisabled ? 1 : 0, } as any; await this.siteModel.update({ id: Number(id) }, payload); return true; } async get(id: string | number, includeSecret = false) { const s = await this.siteModel.findOne({ where: { id: Number(id) } }); if (!s) return null; if (includeSecret) return s; const { consumerKey, consumerSecret, emailPswd, ...rest } = s as any; return rest; } async list(param: { current?: number; pageSize?: number; keyword?: string; isDisabled?: boolean; ids?: string }, includeSecret = false) { const { current = 1, pageSize = 10, keyword, isDisabled, ids } = (param || {}) as any; const where: any = {}; if (keyword) where.siteName = Like(`%${keyword}%`); if (typeof isDisabled === 'boolean') where.isDisabled = isDisabled ? 1 : 0; if (ids) { const numIds = String(ids) .split(',') .filter(Boolean) .map((i) => Number(i)) .filter((v) => !Number.isNaN(v)); if (numIds.length > 0) where.id = In(numIds); } const [items, total] = await this.siteModel.findAndCount({ where, skip: (current - 1) * pageSize, take: pageSize }); const data = includeSecret ? items : items.map((s: any) => { const { consumerKey, consumerSecret, ...rest } = s; return rest; }); return { items: data, total, current, pageSize }; } async disable(id: string | number, disabled: boolean) { await this.siteModel.update({ id: Number(id) }, { isDisabled: disabled ? 1 : 0 }); return true; } }