strapi/packages/core/data-transfer/lib/providers/local-strapi-destination-provider.ts

79 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-10-20 09:52:18 +02:00
// import { createLogger } from '@strapi/logger';
2022-10-19 15:43:52 +02:00
import chalk from 'chalk';
2022-10-20 09:52:18 +02:00
import { Duplex } from 'stream-chain';
import type { IDestinationProvider, IMetadata, ProviderType } from '../../types';
2022-10-19 15:43:52 +02:00
interface ILocalStrapiDestinationProviderOptions {
getStrapi(): Promise<Strapi.Strapi>;
}
2022-10-20 10:04:12 +02:00
// TODO: getting some type errors with @strapi/logger that need to be resolved first
2022-10-20 09:52:18 +02:00
// const log = createLogger();
const log = console;
2022-10-19 15:43:52 +02:00
2022-10-20 10:01:36 +02:00
export const createLocalStrapiDestinationProvider = (options: ILocalStrapiDestinationProviderOptions) => {
return new LocalStrapiDestinationProvider(options);
};
class LocalStrapiDestinationProvider implements IDestinationProvider {
2022-10-20 09:52:18 +02:00
name: string = 'destination::local-strapi';
2022-10-19 15:43:52 +02:00
type: ProviderType = 'destination';
options: ILocalStrapiDestinationProviderOptions;
strapi?: Strapi.Strapi;
constructor(options: ILocalStrapiDestinationProviderOptions) {
this.options = options;
}
async bootstrap(): Promise<void> {
this.strapi = await this.options.getStrapi();
}
async close(): Promise<void> {
2022-10-20 09:52:18 +02:00
await this.strapi?.destroy?.();
2022-10-19 15:43:52 +02:00
}
2022-10-20 09:52:18 +02:00
// TODO
2022-10-19 15:43:52 +02:00
getMetadata(): IMetadata | Promise<IMetadata> {
2022-10-20 09:52:18 +02:00
return {};
2022-10-19 15:43:52 +02:00
}
2022-10-20 09:52:18 +02:00
getEntitiesStream(): Duplex {
2022-10-19 15:43:52 +02:00
const self = this;
2022-10-20 09:52:18 +02:00
return new Duplex({
2022-10-19 15:43:52 +02:00
objectMode: true,
async write(entity, _encoding, callback) {
if (!self.strapi) {
callback(new Error('Strapi instance not found'));
}
const { type: uid, id, data } = entity;
try {
await strapi.entityService.create(uid, { data });
2022-10-20 09:52:18 +02:00
} catch (e:any) { // TODO: remove "any" cast
2022-10-19 15:43:52 +02:00
log.warn(
chalk.bold(`Failed to import ${chalk.yellowBright(uid)} (${chalk.greenBright(id)})`)
);
e.details.errors
2022-10-20 09:52:18 +02:00
.map((err:any, i:number) => { // TODO: add correct error type
2022-10-19 15:43:52 +02:00
const info = {
uid: chalk.yellowBright(`[${uid}]`),
path: chalk.blueBright(`[${err.path.join('.')}]`),
id: chalk.greenBright(`[${id}]`),
message: err.message,
};
return `(${i}) ${info.uid}${info.id}${info.path}: ${info.message}`;
})
2022-10-20 09:52:18 +02:00
.forEach((message:string) => log.warn(message));
2022-10-19 15:43:52 +02:00
} finally {
callback();
}
},
});
}
}