Skip to content

Commit

Permalink
refactor: per review (API, tests)
Browse files Browse the repository at this point in the history
  • Loading branch information
lihbr committed Sep 11, 2024
1 parent 83ccf1f commit 143943b
Show file tree
Hide file tree
Showing 27 changed files with 397 additions and 2,075 deletions.
12 changes: 6 additions & 6 deletions src/Migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export class Migration<
/**
* @internal
*/
documents: {
_documents: {
document: TMigrationDocuments
params: PrismicMigrationDocumentParams
}[] = []
Expand All @@ -143,7 +143,7 @@ export class Migration<
/**
* @internal
*/
assets: Map<MigrationAsset["file"], MigrationAsset> = new Map()
_assets: Map<MigrationAsset["file"], MigrationAsset> = new Map()

createAsset(
asset: Asset | FilledImageFieldImage | FilledLinkToMediaField,
Expand Down Expand Up @@ -226,11 +226,11 @@ export class Migration<

validateAssetMetadata(asset)

const maybeAsset = this.assets.get(asset.id)
const maybeAsset = this._assets.get(asset.id)

if (maybeAsset) {
// Consolidate existing asset with new asset value if possible
this.assets.set(asset.id, {
this._assets.set(asset.id, {
...maybeAsset,
notes: asset.notes || maybeAsset.notes,
credits: asset.credits || maybeAsset.credits,
Expand All @@ -240,7 +240,7 @@ export class Migration<
),
})
} else {
this.assets.set(asset.id, asset)
this._assets.set(asset.id, asset)
}

return {
Expand All @@ -262,7 +262,7 @@ export class Migration<
documentTitle: PrismicMigrationDocumentParams["documentTitle"],
params: Omit<PrismicMigrationDocumentParams, "documentTitle"> = {},
): ExtractMigrationDocumentType<TMigrationDocuments, TType> {
this.documents.push({
this._documents.push({
document,
params: { documentTitle, ...params },
})
Expand Down
123 changes: 53 additions & 70 deletions src/WriteClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { devMsg } from "./lib/devMsg"
import { isAssetTagID } from "./lib/isAssetTagID"
import { pLimit } from "./lib/pLimit"
import type { AssetMap, DocumentMap } from "./lib/patchMigrationDocumentData"
import { patchMigrationDocumentData } from "./lib/patchMigrationDocumentData"
Expand Down Expand Up @@ -232,20 +231,11 @@ export type WriteClientConfig = {
writeToken: string

/**
* An explicit Prismic Migration API key that allows working with the
* Migration API. If none is provided, the client will pick a random one to
* authenticate your requests.
* A Prismic Migration API key that allows working with the Migration API.
*
* @remarks
* These keys are the same for all Prismic users. They are only useful while
* the Migration API is in beta to reduce load. It should be one of:
*
* - `cSaZlfkQlF9C6CEAM2Del6MNX9WonlV86HPbeEJL`
* - `pZCexCajUQ4jriYwIGSxA1drZrFxDyFf1S0D1K0P`
* - `Yc0mfrkGDw8gaaGKTrzwC3QUZDajv6k73DA99vWN`
* - `ySzSEbVMAb5S1oSCQfbVG4mbh9Cb8wlF7BCvKI0L`
* - `g2DA3EKWvx8uxVYcNFrmT5nJpon1Vi9V4XcOibJD`
* - `CCNIlI0Vz41J66oFwsHUXaZa6NYFIY6z7aDF62Bc`
* If no key is provided, the client will use one of the demo key available
* which has stricter rate limiting rules enforced.
*/
migrationAPIKey?: string

Expand Down Expand Up @@ -345,8 +335,8 @@ export class WriteClient<
type: "start",
data: {
pending: {
documents: migration.documents.length,
assets: migration.assets.size,
documents: migration._documents.length,
assets: migration._assets.size,
},
},
})
Expand All @@ -361,8 +351,8 @@ export class WriteClient<
type: "end",
data: {
migrated: {
documents: migration.documents.length,
assets: migration.assets.size,
documents: migration._documents.length,
assets: migration._assets.size,
},
},
})
Expand Down Expand Up @@ -414,7 +404,7 @@ export class WriteClient<
// Create assets
let i = 0
let created = 0
for (const [_, migrationAsset] of migration.assets) {
for (const [_, migrationAsset] of migration._assets) {
if (
typeof migrationAsset.id === "string" &&
assets.has(migrationAsset.id)
Expand All @@ -424,8 +414,8 @@ export class WriteClient<
data: {
reason: "already exists",
current: ++i,
remaining: migration.assets.size - i,
total: migration.assets.size,
remaining: migration._assets.size - i,
total: migration._assets.size,
asset: migrationAsset,
},
})
Expand All @@ -435,8 +425,8 @@ export class WriteClient<
type: "assets:creating",
data: {
current: ++i,
remaining: migration.assets.size - i,
total: migration.assets.size,
remaining: migration._assets.size - i,
total: migration._assets.size,
asset: migrationAsset,
},
})
Expand Down Expand Up @@ -538,7 +528,7 @@ export class WriteClient<

// We create an array with non-master locale documents last because
// we need their master locale document to be created first.
for (const { document, params } of migration.documents) {
for (const { document, params } of migration._documents) {
if (document.lang === masterLocale) {
sortedDocuments.unshift({ document, params })
} else {
Expand Down Expand Up @@ -660,13 +650,13 @@ export class WriteClient<
}: { reporter?: (event: MigrateReporterEvents) => void } & FetchParams = {},
): Promise<void> {
let i = 0
for (const { document, params } of migration.documents) {
for (const { document, params } of migration._documents) {
reporter?.({
type: "documents:updating",
data: {
current: ++i,
remaining: migration.documents.length - i,
total: migration.documents.length,
remaining: migration._documents.length - i,
total: migration._documents.length,
document,
documentParams: params,
},
Expand All @@ -691,7 +681,7 @@ export class WriteClient<
reporter?.({
type: "documents:updated",
data: {
updated: migration.documents.length,
updated: migration._documents.length,
},
})
}
Expand All @@ -703,19 +693,20 @@ export class WriteClient<
*
* @returns A paginated response containing the result of the query.
*/
async getAssets({
private async getAssets({
pageSize,
cursor,
assetType,
keyword,
ids,
tags,
// assetType,
// keyword,
// ids,
// tags,
...params
}: GetAssetsParams & FetchParams = {}): Promise<GetAssetsReturnType> {
}: Pick<GetAssetsParams, "pageSize" | "cursor"> &
FetchParams = {}): Promise<GetAssetsReturnType> {
// Resolve tags if any
if (tags && tags.length) {
tags = await this.resolveAssetTagIDs(tags, params)
}
// if (tags && tags.length) {
// tags = await this.resolveAssetTagIDs(tags, params)
// }

const url = new URL("assets", this.assetAPIEndpoint)

Expand All @@ -727,26 +718,26 @@ export class WriteClient<
url.searchParams.set("cursor", cursor)
}

if (assetType) {
url.searchParams.set("assetType", assetType)
}
// if (assetType) {
// url.searchParams.set("assetType", assetType)
// }

if (keyword) {
url.searchParams.set("keyword", keyword)
}
// if (keyword) {
// url.searchParams.set("keyword", keyword)
// }

if (ids) {
ids.forEach((id) => url.searchParams.append("ids", id))
}
// if (ids) {
// ids.forEach((id) => url.searchParams.append("ids", id))
// }

if (tags) {
tags.forEach((tag) => url.searchParams.append("tags", tag))
}
// if (tags) {
// tags.forEach((tag) => url.searchParams.append("tags", tag))
// }

const {
items,
total,
missing_ids,
// missing_ids,
cursor: nextCursor,
} = await this.fetch<GetAssetsResult>(
url.toString(),
Expand All @@ -756,16 +747,16 @@ export class WriteClient<
return {
results: items,
total_results_size: total,
missing_ids: missing_ids || [],
// missing_ids: missing_ids || [],
next: nextCursor
? () =>
this.getAssets({
pageSize,
cursor: nextCursor,
assetType,
keyword,
ids,
tags,
// assetType,
// keyword,
// ids,
// tags,
...params,
})
: undefined,
Expand Down Expand Up @@ -965,16 +956,16 @@ export class WriteClient<
private _resolveAssetTagIDsLimit = pLimit()

/**
* Resolves asset tag IDs from tag names or IDs.
* Resolves asset tag IDs from tag names.
*
* @param tagNamesOrIDs - An array of tag names or IDs to resolve.
* @param tagNames - An array of tag names to resolve.
* @param params - Whether or not missing tags should be created and
* additional fetch parameters.
*
* @returns An array of resolved tag IDs.
*/
private async resolveAssetTagIDs(
tagNamesOrIDs: string[] = [],
tagNames: string[] = [],
{ createTags, ...params }: { createTags?: boolean } & FetchParams = {},
): Promise<string[]> {
return this._resolveAssetTagIDsLimit(async () => {
Expand All @@ -985,23 +976,15 @@ export class WriteClient<
}

const resolvedTagIDs = []
for (const tagNameOrID of tagNamesOrIDs) {
if (isAssetTagID(tagNameOrID)) {
resolvedTagIDs.push(tagNameOrID)
continue
}

for (const tagName of tagNames) {
// Tag does not exists yet, we create it if `createTags` is set
if (!existingTagMap[tagNameOrID] && createTags) {
existingTagMap[tagNameOrID] = await this.createAssetTag(
tagNameOrID,
params,
)
if (!existingTagMap[tagName] && createTags) {
existingTagMap[tagName] = await this.createAssetTag(tagName, params)
}

// Add tag if found
if (existingTagMap[tagNameOrID]) {
resolvedTagIDs.push(existingTagMap[tagNameOrID].id)
if (existingTagMap[tagName]) {
resolvedTagIDs.push(existingTagMap[tagName].id)
}
}

Expand Down
3 changes: 1 addition & 2 deletions src/createClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ export interface CreateClient {
* createClient("https://qwerty.cdn.prismic.io/api/v2")
* ```
*
* @typeParam TDocuments - A map of Prismic document type IDs mapped to their
* TypeScript type.
* @typeParam TDocuments - A union of Prismic document types for the repository.
*
* @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
* API V2 endpoint for the repository.
Expand Down
3 changes: 1 addition & 2 deletions src/createMigration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ export interface CreateMigration {
* createMigration()
* ```
*
* @typeParam TDocuments - A map of Prismic document type IDs mapped to their
* TypeScript type.
* @typeParam TDocuments - A union of Prismic document types for the repository.
*
* @returns A migration instance to prepare your migration.
*/
Expand Down
3 changes: 1 addition & 2 deletions src/createWriteClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ export interface CreateWriteClient {
* createWriteClient("qwerty", { writeToken: "***" })
* ```
*
* @typeParam TDocuments - A map of Prismic document type IDs mapped to their
* TypeScript type.
* @typeParam TDocuments - A union of Prismic document types for the repository.
*
* @param repositoryName - The Prismic repository name for the repository.
* @param options - Configuration that determines how content will be queried
Expand Down
22 changes: 11 additions & 11 deletions src/getRepositoryName.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
import { PrismicError } from "./errors/PrismicError"

/**
* Get a Prismic repository's name from its standard Prismic Rest API V2 or
* Get a Prismic repository's name from its standard Prismic Document API or
* GraphQL endpoint.
*
* @typeParam RepositoryEndpoint - Prismic Rest API V2 endpoint for the
* repository.
*
* @param repositoryEndpoint - Prismic Rest API V2 endpoint for the repository.
* @param repositoryEndpoint - Prismic Document API endpoint for the repository.
*
* @returns The Prismic repository's name.
*
* @throws {@link Error} Thrown if an invalid Prismic Rest API V2 endpoint is
* @throws {@link Error} Thrown if an invalid Prismic Document API endpoint is
* provided.
*/
export const getRepositoryName = (repositoryEndpoint: string): string => {
try {
const parts = new URL(repositoryEndpoint).hostname.split(".")
const hostname = new URL(repositoryEndpoint).hostname

// [subdomain, domain, tld]
if (parts.length > 2) {
return parts[0]
if (
hostname.endsWith("prismic.io") || // Production
hostname.endsWith("wroom.io") || // Staging
hostname.endsWith("wroom.test") // Dev
) {
return hostname.split(".")[0]
}
} catch {}

throw new PrismicError(
`An invalid Prismic Rest API V2 endpoint was provided: ${repositoryEndpoint}`,
`An invalid Prismic Document API endpoint was provided: ${repositoryEndpoint}`,
undefined,
undefined,
)
Expand Down
15 changes: 0 additions & 15 deletions src/lib/isAssetTagID.ts

This file was deleted.

Loading

0 comments on commit 143943b

Please sign in to comment.