-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslice-add-variation.ts
More file actions
77 lines (66 loc) · 2.15 KB
/
slice-add-variation.ts
File metadata and controls
77 lines (66 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import type { SharedSlice } from "@prismicio/types-internal/lib/customtypes";
import { camelCase } from "change-case";
import { getAdapter } from "../adapters";
import { getHost, getToken } from "../auth";
import { getSlices, updateSlice } from "../clients/custom-types";
import { CommandError, createCommand, type CommandConfig } from "../lib/command";
import { UnknownRequestError } from "../lib/request";
import { getRepositoryName } from "../project";
const config = {
name: "prismic slice add-variation",
description: "Add a variation to a slice.",
positionals: {
name: { description: "Name of the variation", required: true },
},
options: {
to: { type: "string", required: true, description: "ID of the slice" },
id: { type: "string", description: "Custom ID for the variation" },
repo: { type: "string", short: "r", description: "Repository domain" },
},
} satisfies CommandConfig;
export default createCommand(config, async ({ positionals, values }) => {
const [name] = positionals;
const { to, id = camelCase(name), repo = await getRepositoryName() } = values;
const adapter = await getAdapter();
const token = await getToken();
const host = await getHost();
const slices = await getSlices({ repo, token, host });
const slice = slices.find((s) => s.id === to);
if (!slice) {
throw new CommandError(`Slice not found: ${to}`);
}
if (slice.variations.some((v) => v.id === id)) {
throw new CommandError(`Variation "${id}" already exists in slice "${to}".`);
}
const updatedSlice: SharedSlice = {
...slice,
variations: [
...slice.variations,
{
id,
name,
description: name,
docURL: "",
imageUrl: "",
version: "",
primary: {},
},
],
};
try {
await updateSlice(updatedSlice, { repo, host, token });
} catch (error) {
if (error instanceof UnknownRequestError) {
const message = await error.text();
throw new CommandError(`Failed to add variation: ${message}`);
}
throw error;
}
try {
await adapter.updateSlice(updatedSlice);
} catch {
await adapter.createSlice(updatedSlice);
}
await adapter.generateTypes();
console.info(`Added variation "${name}" (id: "${id}") to slice "${to}"`);
});