-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
73 lines (65 loc) · 2.49 KB
/
index.ts
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
import { createClient } from "contentful-management";
import { Entry } from "contentful-management/types";
import { getEntry } from "./lib/contentful";
export interface UmzugContentfulOptions {
spaceId: string;
environmentId: string;
contentfulManagementToken: string;
locale?: string;
migrationEntryId?: string;
migrationContentTypeId?: string;
}
export class ContentfulStorage {
private client;
private readonly environmentId: string;
private readonly spaceId: string;
private readonly locale: string;
private readonly migrationEntryId: string;
private readonly migrationContentTypeId: string;
constructor({
spaceId,
environmentId,
contentfulManagementToken,
locale = "en-US",
migrationEntryId = "umzugMigrationDataEntry",
migrationContentTypeId = "umzugMigrationData",
}: UmzugContentfulOptions) {
this.client = createClient({
space: spaceId,
accessToken: contentfulManagementToken,
});
this.environmentId = environmentId;
this.spaceId = spaceId;
this.locale = locale;
this.migrationEntryId = migrationEntryId;
this.migrationContentTypeId = migrationContentTypeId;
}
private async getContentfulEntryWithLoggedMigrations(): Promise<Entry> {
const space = await this.client.getSpace(this.spaceId);
const environment = await space.getEnvironment(this.environmentId);
return getEntry(environment, {
locale: this.locale,
migrationEntryId: this.migrationEntryId,
migrationContentTypeId: this.migrationContentTypeId,
});
}
private async updateLoggedMigrations(migrations: string[]) {
const loggedMigrationsEntry: Entry = await this.getContentfulEntryWithLoggedMigrations();
loggedMigrationsEntry.fields.migrationData[this.locale] = migrations;
await loggedMigrationsEntry.update();
}
async logMigration({ name: migrationName }: { name: string }): Promise<void> {
const loggedMigrations = await this.executed();
const updatedMigrations = [...loggedMigrations, migrationName];
await this.updateLoggedMigrations(updatedMigrations);
}
async unlogMigration({ name: migrationName }: { name: string }): Promise<void> {
const loggedMigrations = await this.executed();
const updatedMigrations = loggedMigrations.filter((name) => name !== migrationName);
await this.updateLoggedMigrations(updatedMigrations);
}
async executed(): Promise<string[]> {
const entry = await this.getContentfulEntryWithLoggedMigrations();
return entry.fields.migrationData[this.locale];
}
}