81 lines
2.8 KiB
TypeScript
81 lines
2.8 KiB
TypeScript
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<Site>;
|
|
|
|
async syncFromConfig(sites: WpSite[] = []) {
|
|
for (const s of sites) {
|
|
const exist = await this.siteModel.findOne({ where: { siteName: s.siteName } });
|
|
const payload: Partial<Site> = {
|
|
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<Site>) {
|
|
await this.siteModel.insert(data as Site);
|
|
return true;
|
|
}
|
|
|
|
async update(id: string | number, data: UpdateSiteDTO) {
|
|
const payload: Partial<Site> = {
|
|
...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;
|
|
}
|
|
} |