Skip to content

Commit

Permalink
rework API types
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanKiral committed Aug 26, 2024
1 parent 7612fd3 commit d0c1285
Show file tree
Hide file tree
Showing 20 changed files with 222 additions and 180 deletions.
16 changes: 14 additions & 2 deletions src/commands/clean/clean.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import chalk from "chalk";

import { logError, LogOptions } from "../../log.js";
import { CleanEntityChoices, cleanEntityChoices, cleanEnvironmentInternal } from "../../modules/importExport/clean.js";
import {
CleanEntityChoices,
cleanEntityChoices,
cleanEnvironmentInternal,
CleanEnvironmentParams,
} from "../../modules/importExport/clean.js";
import { resolveIncludeExcludeCliParams } from "../../modules/importExport/utils/includeExclude.js";
import { requestConfirmation } from "../../modules/sync/utils/consoleHelpers.js";
import { RegisterCommand } from "../../types/yargs.js";
import { createClient } from "../../utils/client.js";
import { omit } from "../../utils/object.js";

export const commandName = "clean";

Expand Down Expand Up @@ -75,7 +82,7 @@ const cleanEnvironmentCli = async (
const client = createClient({ environmentId: params.environmentId, apiKey: params.apiKey, commandName });

try {
await cleanEnvironmentInternal(params, client);
await cleanEnvironmentInternal(resolveParams(params), client);
} catch (e) {
handleError(params, e);
}
Expand All @@ -92,3 +99,8 @@ const handleError = (

process.exit(1);
};

const resolveParams = (params: CleanEnvironmentCliParams): CleanEnvironmentParams => ({
...omit(params, ["include", "exclude"]),
...resolveIncludeExcludeCliParams(params),
});
10 changes: 9 additions & 1 deletion src/commands/importExport/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import {
ExportEntityChoices,
exportEntityChoices,
exportEnvironmentInternal,
ExportEnvironmentParams,
} from "../../modules/importExport/export.js";
import { resolveIncludeExcludeCliParams } from "../../modules/importExport/utils/includeExclude.js";
import { RegisterCommand } from "../../types/yargs.js";
import { createClient } from "../../utils/client.js";
import { simplifyErrors } from "../../utils/error.js";
import { omit } from "../../utils/object.js";

const commandName = "export";

Expand Down Expand Up @@ -68,9 +71,14 @@ const exportEnvironmentCli = async (params: ExportEnvironmentCliParams): Promise
});

try {
await exportEnvironmentInternal(client, params);
await exportEnvironmentInternal(client, resolveParams(params));
} catch (e) {
logError(params, `${JSON.stringify(e, Object.getOwnPropertyNames(e))}\nStopping export...`);
process.exit(1);
}
};

const resolveParams = (params: ExportEnvironmentCliParams): ExportEnvironmentParams => ({
...omit(params, ["include", "exclude"]),
...resolveIncludeExcludeCliParams(params),
});
10 changes: 9 additions & 1 deletion src/commands/importExport/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import {
ImportEntityChoices,
importEntityChoices,
importEnvironmentInternal,
ImportEnvironmentParams,
} from "../../modules/importExport/import.js";
import { resolveIncludeExcludeCliParams } from "../../modules/importExport/utils/includeExclude.js";
import { RegisterCommand } from "../../types/yargs.js";
import { createClient } from "../../utils/client.js";
import { simplifyErrors } from "../../utils/error.js";
import { omit } from "../../utils/object.js";

const commandName = "import";

Expand Down Expand Up @@ -71,9 +74,14 @@ const importEnvironmentCli = async (params: ImportEnvironmentCliParams) => {
});

try {
await importEnvironmentInternal(client, params);
await importEnvironmentInternal(client, resolveParams(params));
} catch (e: unknown) {
logError(params, `${JSON.stringify(e, Object.getOwnPropertyNames(e))}\nStopping import...`);
process.exit(1);
}
};

const resolveParams = (params: ImportEnvironmentCliParams): ImportEnvironmentParams => ({
...omit(params, ["include", "exclude"]),
...resolveIncludeExcludeCliParams(params),
});
15 changes: 9 additions & 6 deletions src/commands/migrations/run/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,17 +170,20 @@ const runMigrationsCli = async (params: RunMigrationsCliParams) => {

const resolveParams = (
params: RunMigrationsCliParams,
): WithErr<RunMigrationsParams> =>
match(params)
): WithErr<RunMigrationsParams> => {
const emptyParams = { next: undefined, name: undefined, range: undefined, all: undefined };

return match(params)
.returnType<WithErr<RunMigrationsParams>>()
.with({ next: P.nonNullable }, ({ next }) => ({ value: { ...params, next } }))
.with({ next: P.nonNullable }, ({ next }) => ({ value: { ...params, ...emptyParams, next } }))
.with({ range: P.nonNullable }, ({ range }) => {
const parsedRange = parseRange(range as string);
if ("err" in parsedRange) {
return parsedRange;
}
return { value: { ...params, range: parsedRange.value } };
return { value: { ...params, ...emptyParams, range: parsedRange.value } };
})
.with({ name: P.nonNullable }, ({ name }) => ({ value: { ...params, name } }))
.with({ all: P.nonNullable }, ({ all }) => ({ value: { ...params, all } }))
.with({ name: P.nonNullable }, ({ name }) => ({ value: { ...params, ...emptyParams, name } }))
.with({ all: P.nonNullable }, ({ all }) => ({ value: { ...params, ...emptyParams, all } }))
.otherwise(() => ({ err: "Invalid parameters" }));
};
95 changes: 27 additions & 68 deletions src/commands/syncContent/run/run.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import { createDeliveryClient } from "@kontent-ai/delivery-sdk";
import { extractAsync, importAsync, migrateAsync } from "@kontent-ai/migration-toolkit";
import chalk from "chalk";
import { match, P } from "ts-pattern";

import { logError, logInfo, LogOptions } from "../../../log.js";
import { requestConfirmation } from "../../../modules/sync/utils/consoleHelpers.js";
import { getItemsCodenames } from "../../../modules/syncContent/syncContent.js";
import { SyncContentRunParams } from "../../../modules/syncContent/syncContentRun.js";
import { logError, LogOptions } from "../../../log.js";
import { syncContentRunIntenal, SyncContentRunParams } from "../../../modules/syncContent/syncContentRun.js";
import { RegisterCommand } from "../../../types/yargs.js";
import { simplifyErrors } from "../../../utils/error.js";
import { omit } from "../../../utils/object.js";
Expand Down Expand Up @@ -140,62 +135,7 @@ type SyncContentRunCliParams =
const syncContentRunCli = async (params: SyncContentRunCliParams) => {
const resolvedParams = resolveParams(params);

if ("filename" in resolvedParams) {
const data = await extractAsync({ filename: params.filename });

await importAsync({
data: data,
environmentId: params.targetEnvironmentId,
apiKey: params.targetApiKey,
});

process.exit(0);
}

const deliveryClient = createDeliveryClient({
environmentId: resolvedParams.sourceEnvironmentId,
previewApiKey: resolvedParams.sourceDeliveryPreviewKey,
defaultQueryConfig: {
usePreviewMode: true,
},
});

const itemsCodenames = await getItemsCodenames(deliveryClient, resolvedParams);

if (!itemsCodenames.length) {
logInfo(params, "standard", `No items to migrate`);
process.exit(0);
}

logInfo(
params,
"standard",
`Syncing ${itemsCodenames.length} items from ${resolvedParams.sourceEnvironmentId} to ${resolvedParams.targetEnvironmentId} ${
itemsCodenames.length < 100 ? `with codenames:\n${itemsCodenames.join("\n")}` : ""
}`,
);

const warningMessage = chalk.yellow(
`⚠ Running this operation may result in changes to the content in environment ${params.targetEnvironmentId}. OK to proceed y/n? (suppress this message with --skipConfirmation parameter)\n`,
);

const confirmed = !params.skipConfirmation ? await requestConfirmation(warningMessage) : true;

if (!confirmed) {
logInfo(params, "standard", chalk.red("Operation aborted."));
process.exit(1);
}

await migrateAsync({
targetEnvironment: { apiKey: params.targetApiKey, environmentId: params.targetEnvironmentId },
sourceEnvironment: {
environmentId: resolvedParams.sourceEnvironmentId,
apiKey: resolvedParams.sourceApiKey,
items: itemsCodenames.map(i => ({ itemCodename: i, languageCodename: resolvedParams.language })),
},
});

logInfo(params, "standard", `All items sucessfuly migrated`);
syncContentRunIntenal(resolvedParams, "sync-content-run");
};

const resolveParams = (params: SyncContentRunCliParams): SyncContentRunParams => {
Expand All @@ -206,12 +146,31 @@ const resolveParams = (params: SyncContentRunCliParams): SyncContentRunParams =>
}

const filterParams = match(params)
.with({ items: P.nonNullable }, ({ items }) => ({ ...ommited, items }))
.with({ byTypesCodenames: P.nonNullable }, ({ byTypesCodenames }) => ({ ...ommited, byTypesCodenames }))
.with({ filter: P.nonNullable }, ({ filter }) => ({ ...ommited, filter }))
.with({ last: P.nonNullable }, ({ last }) => ({ ...ommited, last }))
.with(
{ items: P.nonNullable, depth: P.nonNullable, sourceDeliveryPreviewKey: P.nonNullable },
({ items, depth, sourceDeliveryPreviewKey }) => ({ ...ommited, items, depth, sourceDeliveryPreviewKey }),
)
.with(
{ items: P.nonNullable },
({ items }) => ({ ...ommited, items }),
)
.with(
{ byTypesCodenames: P.nonNullable, sourceDeliveryPreviewKey: P.nonNullable },
({ byTypesCodenames, sourceDeliveryPreviewKey }) => ({ ...ommited, byTypesCodenames, sourceDeliveryPreviewKey }),
)
.with(
{ filter: P.nonNullable, sourceDeliveryPreviewKey: P.nonNullable },
({ filter, sourceDeliveryPreviewKey }) => ({ ...ommited, filter, sourceDeliveryPreviewKey }),
)
.with(
{ last: P.nonNullable, sourceDeliveryPreviewKey: P.nonNullable },
({ last, sourceDeliveryPreviewKey }) => ({ ...ommited, last, sourceDeliveryPreviewKey }),
)
.otherwise(() => {
logError(params, "You need to provide exactly one from parameters: items, byTypesCodenames, filter or last");
logError(
params,
"You need to provide exactly one from parameters: --items or --items with --depth, --filter, --byTypesCodenames, --last with --sourceDeliveryPeviewKey",
);
process.exit(1);
});

Expand Down
11 changes: 9 additions & 2 deletions src/commands/syncModel/diff/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ const diffEnvironmentsCli = async (params: DiffEnvironmentsCliParams) => {
await diffEnvironmentsInternal(resolvedParams, commandName);
};

const resolveParams = (params: DiffEnvironmentsCliParams): DiffEnvironmentsParams =>
match(params)
const resolveParams = (params: DiffEnvironmentsCliParams): DiffEnvironmentsParams => {
const baseParams = match(params)
.with(
{ sourceEnvironmentId: P.nonNullable, sourceApiKey: P.nonNullable },
({ sourceEnvironmentId, sourceApiKey }) => ({ ...params, sourceEnvironmentId, sourceApiKey }),
Expand All @@ -99,3 +99,10 @@ const resolveParams = (params: DiffEnvironmentsCliParams): DiffEnvironmentsParam
);
process.exit(1);
});

if (!params.advanced) {
return { ...baseParams, advanced: false };
}

return { ...baseParams, advanced: true };
};
9 changes: 5 additions & 4 deletions src/modules/importExport/clean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,14 @@ export const cleanEntityChoices = cleanEntityDefinitions.map(e => e.name);

export type CleanEntityChoices = typeof cleanEntityChoices[number];

export type CleanEnvironmentParams =
& Readonly<{
export type CleanEnvironmentParams = Readonly<
& {
environmentId: string;
apiKey: string;
}>
}
& IncludeExclude<CleanEntityChoices>
& LogOptions;
& LogOptions
>;

export const cleanEnvironment = async (params: CleanEnvironmentParams) => {
const client = createClient({ environmentId: params.environmentId, apiKey: params.apiKey, commandName: "clean-API" });
Expand Down
9 changes: 5 additions & 4 deletions src/modules/importExport/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,15 @@ export const exportEntityChoices = exportEntityDefinitions.map(e => e.name);

export type ExportEntityChoices = typeof exportEntityChoices[number];

export type ExportEnvironmentParams =
& Readonly<{
export type ExportEnvironmentParams = Readonly<
& {
environmentId: string;
fileName?: string;
apiKey: string;
}>
}
& IncludeExclude<ExportEntityChoices>
& LogOptions;
& LogOptions
>;

export const exportEnvironment = async (params: ExportEnvironmentParams) => {
const client = createClient({
Expand Down
11 changes: 5 additions & 6 deletions src/modules/importExport/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,15 @@ export const importEntityChoices = importEntityDefinitions.filter(e => !("isDepe

export type ImportEntityChoices = typeof importEntityChoices[number];

export type ImportEnvironmentParams =
& Readonly<{
export type ImportEnvironmentParams = Readonly<
& {
environmentId: string;
fileName: string;
apiKey: string;
include?: ReadonlyArray<string>;
exclude?: ReadonlyArray<string>;
}>
}
& IncludeExclude<ImportEntityChoices>
& LogOptions;
& LogOptions
>;

export const importEnvironment = async (params: ImportEnvironmentParams) => {
const client = createClient({
Expand Down
23 changes: 19 additions & 4 deletions src/modules/importExport/utils/includeExclude.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
export type IncludeExclude<Choices extends string> =
| { include: ReadonlyArray<Choices> }
| { exclude?: ReadonlyArray<Choices> }; // Exclude is optional because it's possible to use the type without
import { match, P } from "ts-pattern";

export type IncludeExclude<Choices extends string> = Readonly<
| { include?: ReadonlyArray<Choices>; exclude?: undefined }
| { exclude?: ReadonlyArray<Choices>; include?: undefined }
>;

export const includeExcludePredicate = (params: IncludeExclude<string>) => (entity: Readonly<{ name: string }>) =>
"include" in params ? params.include.includes(entity.name) : !params.exclude?.includes(entity.name);
match(params)
.with({ include: P.nonNullable }, ({ include }) => include.includes(entity.name))
.with({ exclude: P.nonNullable }, ({ exclude }) => !exclude.includes(entity.name))
.otherwise(() => true);

export const resolveIncludeExcludeCliParams = <Choices extends string>(
params: { include?: ReadonlyArray<Choices>; exclude?: ReadonlyArray<Choices> },
): IncludeExclude<Choices> =>
match(params)
.returnType<IncludeExclude<Choices>>()
.with({ include: P.nonNullable }, ({ include }) => ({ ...params, include, exclude: undefined }))
.with({ exclude: P.nonNullable }, ({ exclude }) => ({ ...params, exclude, include: undefined }))
.otherwise(() => ({ ...params, include: undefined, exclude: undefined }));
9 changes: 5 additions & 4 deletions src/modules/migrations/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ import {
getMigrationName,
} from "./utils/migrationUtils.js";

export type AddMigrationParams =
& Readonly<{
export type AddMigrationParams = Readonly<
& {
name: string;
migrationsFolder?: string;
timestamp: boolean;
type: string;
}>
& LogOptions;
}
& LogOptions
>;

export const addMigration = async (params: AddMigrationParams) => {
if (params.type !== "js" && params.type !== "ts") {
Expand Down
Loading

0 comments on commit d0c1285

Please sign in to comment.