Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bulk-update)!: replace bulk by bulk-update endpoint #15

Merged
merged 7 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,36 @@

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

## [2.0.0-alpha.1](https://github.com/prismicio/prismic-custom-types-client/compare/v2.0.0-alpha.0...v2.0.0-alpha.1) (2024-05-29)

## [2.0.0-alpha.0](https://github.com/prismicio/prismic-custom-types-client/compare/v1.1.0...v2.0.0-alpha.0) (2024-05-29)


### ⚠ BREAKING CHANGES

* **bulk-update:** drop support for bulk endpoint

### Features

* **bulk-update:** replace bulk by bulk-update endpoint ([abfcd13](https://github.com/prismicio/prismic-custom-types-client/commit/abfcd13b672d6bef7f119af2435db49373886741))
* pass arbitrary options to `fetch()` with the `fetchOptions` parameter ([#9](https://github.com/prismicio/prismic-custom-types-client/issues/9)) ([ae76fe8](https://github.com/prismicio/prismic-custom-types-client/commit/ae76fe8e6fcd84f2e79745e57f687625325d0a94))
* support bulk transactions ([#10](https://github.com/prismicio/prismic-custom-types-client/issues/10)) ([38968f7](https://github.com/prismicio/prismic-custom-types-client/commit/38968f779b00ce8d62495438c14b87b2fe3c8f13))


### Bug Fixes

* make `@prismicio/client` a peer dependency ([#14](https://github.com/prismicio/prismic-custom-types-client/issues/14)) ([99d2b67](https://github.com/prismicio/prismic-custom-types-client/commit/99d2b675f7e974cff7ad1ea74f8f4f3c37884e98))
* replace `@prismicio/types` with `@prismicio/client` ([#11](https://github.com/prismicio/prismic-custom-types-client/issues/11)) ([77474e6](https://github.com/prismicio/prismic-custom-types-client/commit/77474e63f6907639f3f3ed8c7a9cee80116e8692))


### Chore

* **deps:** update all dependencies ([#12](https://github.com/prismicio/prismic-custom-types-client/issues/12)) ([2c5330e](https://github.com/prismicio/prismic-custom-types-client/commit/2c5330e41c921f7d536db4a84c021ffd4776ed74))
* **release:** 1.2.0 ([c662c3f](https://github.com/prismicio/prismic-custom-types-client/commit/c662c3f57464653e654ae4e48d6506b6c44ba6c0))
* **release:** 1.3.0 ([bd7f977](https://github.com/prismicio/prismic-custom-types-client/commit/bd7f9774e505e39262ab030e66213d88341f19cd))
* **release:** 1.3.1 ([1fff28f](https://github.com/prismicio/prismic-custom-types-client/commit/1fff28fc39e40c672f8002fbcb00af8792f331b3))
* **releases:** release alpha as major ([82948fb](https://github.com/prismicio/prismic-custom-types-client/commit/82948fbc887e246244718b37f0d0e230ca5db827))

### [1.3.1](https://github.com/prismicio/prismic-custom-types-client/compare/v1.3.0...v1.3.1) (2024-04-17)


Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@prismicio/custom-types-client",
"version": "1.3.1",
"version": "2.0.0-alpha.1",
"description": "JavaScript client to interact with the Prismic Custom Types API",
"keywords": [
"typescript",
Expand Down Expand Up @@ -34,8 +34,8 @@
"lint": "eslint --ext .js,.ts .",
"prepare": "npm run build",
"release": "npm run test && standard-version && git push --follow-tags && npm run build && npm publish",
"release:alpha": "npm run test && standard-version --release-as minor --prerelease alpha && git push --follow-tags && npm run build && npm publish --tag alpha",
"release:alpha:dry": "standard-version --release-as minor --prerelease alpha --dry-run",
"release:alpha": "npm run test && standard-version --release-as major --prerelease alpha && git push --follow-tags && npm run build && npm publish --tag alpha",
"release:alpha:dry": "standard-version --release-as major --prerelease alpha --dry-run",
"release:dry": "standard-version --dry-run",
"size": "size-limit",
"test": "npm run lint && npm run types && npm run unit && npm run build && npm run size",
Expand Down
61 changes: 33 additions & 28 deletions src/bulk.ts → src/bulkUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,53 @@ import * as prismic from "@prismicio/client";
/**
* The type of a bulk operation.
*/
export const BulkOperationType = {
export const BulkUpdateOperationType = {
CustomTypeInsert: "CUSTOM_TYPE_INSERT",
CustomTypeUpdate: "CUSTOM_TYPE_UPDATE",
CustomTypeDelete: "CUSTOM_TYPE_DELETE",
SliceInsert: "SLICE_INSERT",
SliceUpdate: "SLICE_UPDATE",
SliceDelete: "SLICE_DELETE",
} as const;
export type BulkOperationType =
(typeof BulkOperationType)[keyof typeof BulkOperationType];
export type BulkUpdateOperationType =
(typeof BulkUpdateOperationType)[keyof typeof BulkUpdateOperationType];

/**
* An object describing a bulk operation.
* An object describing a bulk update operation.
*/
export type BulkOperation =
export type BulkUpdateOperation =
| {
type: typeof BulkOperationType.CustomTypeInsert;
type: typeof BulkUpdateOperationType.CustomTypeInsert;
id: string;
payload: prismic.CustomTypeModel;
}
| {
type: typeof BulkOperationType.CustomTypeUpdate;
type: typeof BulkUpdateOperationType.CustomTypeUpdate;
id: string;
payload: prismic.CustomTypeModel;
}
| {
type: typeof BulkOperationType.CustomTypeDelete;
type: typeof BulkUpdateOperationType.CustomTypeDelete;
id: string;
payload: Pick<prismic.CustomTypeModel, "id">;
}
| {
type: typeof BulkOperationType.SliceInsert;
type: typeof BulkUpdateOperationType.SliceInsert;
id: string;
payload: prismic.SharedSliceModel;
}
| {
type: typeof BulkOperationType.SliceUpdate;
type: typeof BulkUpdateOperationType.SliceUpdate;
id: string;
payload: prismic.SharedSliceModel;
}
| {
type: typeof BulkOperationType.SliceDelete;
type: typeof BulkUpdateOperationType.SliceDelete;
id: string;
payload: Pick<prismic.SharedSliceModel, "id">;
};

export type BulkTransactionModels = {
export type BulkUpdateTransactionModels = {
customTypes?: prismic.CustomTypeModel[];
slices?: prismic.SharedSliceModel[];
};
Expand Down Expand Up @@ -85,24 +85,29 @@ const processDiff = <
};

/**
* Create a bulk transaction instance to pass to a Custom Types Client `bulk()`
* method.
* Create a bulk update transaction instance to pass to a Custom Types Client
* `bulkUpdate()` method.
*/
export const createBulkTransaction = (
...args: ConstructorParameters<typeof BulkTransaction>
): BulkTransaction => new BulkTransaction(...args);
export const createBulkUpdateTransaction = (
...args: ConstructorParameters<typeof BulkUpdateTransaction>
): BulkUpdateTransaction => new BulkUpdateTransaction(...args);

export class BulkTransaction {
operations: BulkOperation[];
export class BulkUpdateTransaction {
operations: BulkUpdateOperation[];

constructor(initialOperations: BulkTransaction | BulkOperation[] = []) {
constructor(
initialOperations: BulkUpdateTransaction | BulkUpdateOperation[] = [],
) {
this.operations =
initialOperations instanceof BulkTransaction
initialOperations instanceof BulkUpdateTransaction
? initialOperations.operations
: initialOperations;
}

fromDiff(before: BulkTransactionModels, after: BulkTransactionModels): void {
fromDiff(
before: BulkUpdateTransactionModels,
after: BulkUpdateTransactionModels,
): void {
processDiff(before.customTypes ?? [], after.customTypes ?? [], {
onInsert: (model) => this.insertCustomType(model),
onUpdate: (model) => this.updateCustomType(model),
Expand All @@ -117,47 +122,47 @@ export class BulkTransaction {

insertCustomType(customType: prismic.CustomTypeModel): void {
this.operations.push({
type: BulkOperationType.CustomTypeInsert,
type: BulkUpdateOperationType.CustomTypeInsert,
id: customType.id,
payload: customType,
});
}

updateCustomType(customType: prismic.CustomTypeModel): void {
this.operations.push({
type: BulkOperationType.CustomTypeUpdate,
type: BulkUpdateOperationType.CustomTypeUpdate,
id: customType.id,
payload: customType,
});
}

deleteCustomType(customType: prismic.CustomTypeModel): void {
this.operations.push({
type: BulkOperationType.CustomTypeDelete,
type: BulkUpdateOperationType.CustomTypeDelete,
id: customType.id,
payload: { id: customType.id },
});
}

insertSlice(slice: prismic.SharedSliceModel): void {
this.operations.push({
type: BulkOperationType.SliceInsert,
type: BulkUpdateOperationType.SliceInsert,
id: slice.id,
payload: slice,
});
}

updateSlice(slice: prismic.SharedSliceModel): void {
this.operations.push({
type: BulkOperationType.SliceUpdate,
type: BulkUpdateOperationType.SliceUpdate,
id: slice.id,
payload: slice,
});
}

deleteSlice(slice: prismic.SharedSliceModel): void {
this.operations.push({
type: BulkOperationType.SliceDelete,
type: BulkUpdateOperationType.SliceDelete,
id: slice.id,
payload: { id: slice.id },
});
Expand Down
71 changes: 24 additions & 47 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@ import type * as prismic from "@prismicio/client";
import type { AbortSignalLike, FetchLike, RequestInitLike } from "./types";

import {
BulkTransactionConfirmationError,
BulkTransactionLimitError,
BulkUpdateHasExistingDocumentsError,
ConflictError,
ForbiddenError,
InvalidAPIResponse,
InvalidPayloadError,
MissingFetchError,
NotFoundError,
PrismicError,
UnauthorizedError,
} from "./errors";

import { BulkOperation, BulkTransaction } from "./bulk";
import { BulkUpdateOperation, BulkUpdateTransaction } from "./bulkUpdate";

/**
* The default endpoint for the Prismic Custom Types API.
Expand Down Expand Up @@ -52,7 +51,8 @@ export type CustomTypesClientConfig = {
/**
* Options provided to the client's `fetch()` on all network requests. These
* options will be merged with internally required options. They can also be
* overriden on a per-query basis using the query's `fetchOptions` parameter.
* overridden on a per-query basis using the query's `fetchOptions`
* parameter.
*/
fetchOptions?: RequestInitLike;
};
Expand Down Expand Up @@ -85,19 +85,6 @@ type FetchParams = {
signal?: AbortSignalLike;
};

/**
* Parameters for the `bulk()` client method.
*/
type BulkParams = {
/**
* Determines if the method stops a bulk request if the changes require
* deleting Prismic documents.
*
* @defaultValue false
*/
deleteDocuments?: boolean;
};

/**
* Create a `RequestInit` object for a POST `fetch` request. The provided body
* will be run through `JSON.stringify`.
Expand Down Expand Up @@ -454,34 +441,33 @@ export class CustomTypesClient {
* @example
*
* ```ts
* const bulkTransaction = createBulkTransaction();
* bulkTransaction.insertCustomType(myCustomType);
* bulkTransaction.deleteSlice(mySlice);
* const bulkUpdateTransaction = createBulkUpdateTransaction();
* bulkUpdateTransaction.insertCustomType(myCustomType);
* bulkUpdateTransaction.deleteSlice(mySlice);
*
* await client.bulk(bulkTransaction);
* await client.bulkUpdate(bulkUpdateTransaction);
* ```
*
* @param operations - A `BulkTransaction` containing all operations or an
* array of objects describing an operation.
* @param operations - A `BulkUpdateTransaction` containing all operations or
* an array of objects describing an operation.
* @param params - Parameters that determine how the method behaves and for
* overriding the client's default configuration.
*
* @returns An array of objects describing the operations.
*/
async bulk(
operations: BulkTransaction | BulkOperation[],
params?: BulkParams & CustomTypesClientMethodParams & FetchParams,
): Promise<BulkOperation[]> {
async bulkUpdate(
operations: BulkUpdateTransaction | BulkUpdateOperation[],
params?: CustomTypesClientMethodParams & FetchParams,
): Promise<BulkUpdateOperation[]> {
const resolvedOperations =
operations instanceof BulkTransaction
operations instanceof BulkUpdateTransaction
? operations.operations
: operations;

await this.fetch(
"./bulk",
"./bulk-update",
params,
createPostFetchRequestInit({
confirmDeleteDocuments: params?.deleteDocuments ?? false,
changes: resolvedOperations,
}),
);
Expand Down Expand Up @@ -564,17 +550,6 @@ export class CustomTypesClient {
return undefined as any;
}

// Accepted
// - Soft limit reached for bulk request (requires confirmation)
case 202: {
const json = await res.json();

throw new BulkTransactionConfirmationError(
"The bulk transaction will delete documents. Confirm before trying again.",
{ url, response: json },
);
}

// Bad Request
// - Invalid body sent
case 400: {
Expand All @@ -594,13 +569,13 @@ export class CustomTypesClient {
// Forbidden
// - Missing token
// - Incorrect token
// - Hard limit reached for bulk request (cannot process)
// - Has existing documents (cannot process)
case 403: {
const json = await res.json();

if ("details" in json) {
throw new BulkTransactionLimitError(
"The bulk transaction reached or surpassed the limit of allowed commands.",
if ("hasExistingDocuments" in json && json.hasExistingDocuments) {
throw new BulkUpdateHasExistingDocumentsError(
"The bulk update changes contain deletion operations for custom types with existing documents.",
xrutayisire marked this conversation as resolved.
Show resolved Hide resolved
{ url, response: json },
);
}
Expand Down Expand Up @@ -633,6 +608,8 @@ export class CustomTypesClient {
}
}

throw new PrismicError("An invalid API response was returned", { url });
throw new InvalidAPIResponse("An invalid API response was returned", {
angeloashmore marked this conversation as resolved.
Show resolved Hide resolved
url,
});
}
}
Loading
Loading