Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
26 changes: 26 additions & 0 deletions documentation/1-promise.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,32 @@ A shortcut method that gives a Promise returning a JSON object.

It is semantically the same as setting [`options.resolveBodyOnly`](2-options.md#resolvebodyonly) to `true` and [`options.responseType`](2-options.md#responsetype) to `'json'`.

### `promise.json(schema)`

**Returns: `Promise<StandardSchemaV1InferOutput<Schema>>`**

A shortcut method that gives a Promise returning a JSON object validated with a [Standard Schema](https://standardschema.dev)-compatible validator, such as [Zod](https://github.com/colinhacks/zod) or [Valibot](https://valibot.dev). The promise resolves with the output of the schema, and the return type is inferred from it.

A custom [`parseJson`](2-options.md#parsejson) option runs first, so the schema receives the parsed body. The `validate` method of the schema may return a Promise.

An empty response body parses to an empty string, the same as for [`promise.json<T>()`](1-promise.md#promisejsont), so the schema receives `''`.

Throws a [`SchemaValidationError`](8-errors.md#schemavalidationerror) when the body does not match the schema.

> [!NOTE]
> A `TypeError` is thrown when the argument does not follow the Standard Schema specification, for example when it has no `~standard.validate` method.

```js
import got from 'got';
import {z} from 'zod';

const userSchema = z.object({name: z.string()});

const user = await got('https://example.com/user').json(userSchema);

console.log(user.name);
```

### `promise.buffer()`

**Returns: `Promise<Uint8Array>`**
Expand Down
2 changes: 2 additions & 0 deletions documentation/2-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,8 @@ The parsing method.
The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.\
It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise.

`.json()` also accepts a [Standard Schema](https://standardschema.dev) validator, in which case the promise resolves with the output of the schema. See [`promise.json(schema)`](1-promise.md#promisejsonschema).

```js
import got from 'got';

Expand Down
29 changes: 28 additions & 1 deletion documentation/8-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ All Got errors contain various metadata, such as:
- `response` (optional) - An instance of Got Response,
- `timings` (optional) - Points to `response.timings`.

> [!NOTE]
> [`SchemaValidationError`](#schemavalidationerror) is the exception: it comes from the user-provided schema instead of the request lifecycle, so the only metadata it adds is the schema `issues`.

#### Capturing async stack traces

Read the article [here](async-stack-traces.md).
Expand All @@ -27,7 +30,7 @@ Read the article [here](async-stack-traces.md).

**Code: `ERR_GOT_REQUEST_ERROR`**

When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. All the errors below inherit this one.
When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. All the errors below inherit this one, except [`SchemaValidationError`](#schemavalidationerror).

### `CacheError`

Expand All @@ -49,6 +52,30 @@ The error code will be `ERR_HTTP_CONTENT_LENGTH_MISMATCH` when the `strictConten

When server response code is 2xx, and parsing body fails. Includes a `response` property.

### `SchemaValidationError`

When the response body does not match the [Standard Schema](https://standardschema.dev) validator passed to [`promise.json(schema)`](1-promise.md#promisejsonschema). Includes an `issues` property with the issues from the schema. Each issue has a `message` and an optional `path`.

It intentionally does not extend [`RequestError`](#requesterror), because the request succeeded. The user-provided schema did not accept the data, so it has no `code`, `options`, `request`, `response` or `timings` property, and it is not passed to [`beforeError` hooks](9-hooks.md#beforeerror).

```js
import got, {SchemaValidationError} from 'got';
import {z} from 'zod';

const userSchema = z.object({name: z.string()});

try {
const user = await got('https://example.com/user').json(userSchema);
console.log(user.name);
} catch (error) {
if (error instanceof SchemaValidationError) {
console.error(error.issues);
} else {
throw error;
}
}
```

### `UploadError`

**Code: `ERR_UPLOAD`**
Expand Down
3 changes: 3 additions & 0 deletions documentation/9-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,9 @@ const instance = got.extend({

Called with a [`RequestError`](8-errors.md#requesterror) instance. The error is passed to the hook right before it's thrown.

> [!NOTE]
> A [`SchemaValidationError`](8-errors.md#schemavalidationerror) is not passed to this hook, because it does not extend `RequestError`.

This hook can return any `Error` instance, allowing you to:
- Return custom error classes for better error handling in your application
- Extend `RequestError` with additional properties
Expand Down
2 changes: 1 addition & 1 deletion documentation/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ See the documentation for other [options](2-options.md#options).

## Errors

Both Promise and Stream APIs throw errors with metadata.
Both Promise and Stream APIs throw errors with metadata, such as `response` and `timings`.

```js
import got from 'got';
Expand Down
7 changes: 7 additions & 0 deletions documentation/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ console.log(result.buzz); // boolean

**Note:**
> - Use `.json<T>()` to get `RequestPromise<T>` with the body-only response.
> - Use `.json(schema)` to validate the body with a [Standard Schema](https://standardschema.dev) validator and get the output type of the schema.
> - Use `.buffer()` or `.text()` for other response types.
> - Without calling these methods, you'll get `RequestPromise<Response<T>>`.
> - Use `signal` and `AbortController` to abort requests.
Expand Down Expand Up @@ -111,6 +112,12 @@ Here's a list of types that Got exports:

### [`RequestPromise<T extends Response | Response['body'] = Response['body']>`](https://github.com/sindresorhus/got/blob/ae04c0e36cf3f5b2e356df7d48a5b19988f935a2/source/as-promise/types.ts#L26)

### [`StandardSchemaV1`](https://github.com/sindresorhus/got/blob/main/source/core/standard-schema.ts)

### [`StandardSchemaV1InferOutput<Schema>`](https://github.com/sindresorhus/got/blob/main/source/core/standard-schema.ts)

### [`StandardSchemaV1Issue`](https://github.com/sindresorhus/got/blob/main/source/core/standard-schema.ts)

### [`Delays`](https://github.com/sindresorhus/got/blob/ae04c0e36cf3f5b2e356df7d48a5b19988f935a2/source/core/timed-out.ts#L14)

### [`Timings`](https://github.com/sindresorhus/got/blob/main/source/core/utils/timer.ts#L19)
Expand Down
3 changes: 2 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ npm install got
### JSON mode

Got has a dedicated option for handling JSON payload.\
Furthermore, the promise exposes a `.json<T>()` function that returns `Promise<T>`.
Furthermore, the promise exposes a `.json<T>()` function that returns `Promise<T>`. It also exposes a `.json(schema)` function that validates the payload with a [Standard Schema](https://standardschema.dev) and infers the type from the schema.

```js
import got from 'got';
Expand Down Expand Up @@ -119,6 +119,7 @@ By default, Got will retry on failure. To disable this option, set [`options.ret
- [x] [Advanced HTTPS API](documentation/5-https.md)
- [x] [HTTP/2 support](documentation/2-options.md#http2)
- [x] [`Response` class](documentation/3-streams.md#response-2)
- [x] [Response validation with Standard Schema](documentation/1-promise.md#promisejsonschema)

#### Timeouts and retries

Expand Down
37 changes: 33 additions & 4 deletions source/as-promise/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import {
normalizeError,
HTTPError,
RetryError,
SchemaValidationError,
type RequestError,
} from '../core/errors.js';
import Request from '../core/index.js';
import type {StandardSchemaV1} from '../core/standard-schema.js';
import isNonReplayableBody from '../core/utils/is-non-replayable-body.js';
import {
decodeUint8Array,
Expand Down Expand Up @@ -36,6 +38,23 @@ const proxiedRequestEvents = [
'downloadProgress',
];

const validateWithSchema = async (value: unknown, schema: StandardSchemaV1): Promise<unknown> => {
// JavaScript users can pass anything, so check the shape before calling into the schema.
const standardSchema = is.object(schema) ? schema['~standard'] : undefined;

if (!is.object(standardSchema) || typeof standardSchema.validate !== 'function') {
throw new TypeError('The `schema` argument must follow the Standard Schema specification');
}

const validationResult = await standardSchema.validate(value);

if (validationResult.issues) {
throw new SchemaValidationError(validationResult.issues);
}

return validationResult.value;
};

export default function asPromise<T>(firstRequest?: Request): RequestPromise<T> {
let globalRequest: Request;
let globalResponse: Response;
Expand Down Expand Up @@ -261,7 +280,7 @@ export default function asPromise<T>(firstRequest?: Request): RequestPromise<T>
};
}

const shortcut = <T>(promiseToAwait: RequestPromise, responseType: Options['responseType']): RequestPromise<T> => {
const shortcut = <T>(promiseToAwait: RequestPromise, responseType: Options['responseType'], schema?: StandardSchemaV1): RequestPromise<T> => {
const newPromise = (async () => {
// Wait until downloading has ended
const response = await promiseToAwait as Response | undefined;
Expand All @@ -275,7 +294,17 @@ export default function asPromise<T>(firstRequest?: Request): RequestPromise<T>

// `parseBody` wraps a decode failure in a `ParseError`, so an unusable encoding is
// reported with the response attached instead of as a bare `TypeError`.
return parseBody(globalResponse, responseType, options.parseJson, options.encoding) as T;
const body = parseBody(globalResponse, responseType, options.parseJson, options.encoding);

if (schema === undefined) {
return body as T;
}

// Awaiting instead of returning the validation promise keeps the caller's frame in the
// async stack trace of a `SchemaValidationError`.
const validatedBody = await validateWithSchema(body, schema);

return validatedBody as T;
})();

// eslint-disable-next-line @typescript-eslint/no-floating-promises
Expand All @@ -288,7 +317,7 @@ export default function asPromise<T>(firstRequest?: Request): RequestPromise<T>
// When custom handlers wrap the promise to transform errors, these methods
// are copied to the handler's promise. Using `this` ensures we await the
// handler's wrapped promise, not the original, so errors propagate correctly.
promise.json = function (this: RequestPromise) {
promise.json = function (this: RequestPromise, schema?: StandardSchemaV1) {
if (globalRequest.options) {
const {headers} = globalRequest.options;

Expand All @@ -297,7 +326,7 @@ export default function asPromise<T>(firstRequest?: Request): RequestPromise<T>
}
}

return shortcut(this, 'json');
return shortcut(this, 'json', schema);
};

promise.buffer = function (this: RequestPromise) {
Expand Down
36 changes: 31 additions & 5 deletions source/as-promise/types.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,40 @@
import {type RequestEvents} from '../core/index.js';
import type {Response} from '../core/response.js';
import type {StandardSchemaV1, StandardSchemaV1InferOutput} from '../core/standard-schema.js';

// eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- Internal recursive shape requires interface; public API remains a type alias.
interface RequestPromiseShape<T extends Response | Response['body'] = Response['body']> extends RequestEvents<RequestPromise<T>> {
/**
A shortcut method that gives a Promise returning a JSON object.
json: {
/**
A shortcut method that gives a Promise returning a JSON object.

It is semantically the same as setting `options.resolveBodyOnly` to `true` and `options.responseType` to `'json'`.
*/
json: <ReturnType>() => RequestPromise<ReturnType>;
It is semantically the same as setting `options.resolveBodyOnly` to `true` and `options.responseType` to `'json'`.
*/
<ReturnType>(schema?: undefined): RequestPromise<ReturnType>;

/**
A shortcut method that gives a Promise returning a JSON object validated with a [Standard Schema](https://standardschema.dev)-compatible validator, such as [Zod](https://github.com/colinhacks/zod) or [Valibot](https://valibot.dev). The promise resolves with the output of the schema, and the return type is inferred from it.

A custom `parseJson` option runs first, so the schema receives the parsed body. The `validate` method of the schema may return a Promise.

An empty response body parses to an empty string, the same as for `.json()`, so the schema receives `''`.

Throws a `SchemaValidationError` when the body does not match the schema.

Throws a `TypeError` when the argument does not follow the Standard Schema specification, for example when it has no `~standard.validate` method.

@example
```
import got from 'got';
import {z} from 'zod';

const userSchema = z.object({name: z.string()});

const user = await got('https://example.com/user').json(userSchema);
```
*/
<Schema extends StandardSchemaV1>(schema: Schema): RequestPromise<StandardSchemaV1InferOutput<Schema>>;
};

/**
A shortcut method that gives a Promise returning a [Uint8Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
Expand Down
35 changes: 35 additions & 0 deletions source/core/errors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import is from '@sindresorhus/is';
import stripUrlAuth from './utils/strip-url-auth.js';
import type {StandardSchemaV1Issue} from './standard-schema.js';
import type {Timings} from './utils/timer.js';
import type Options from './options.js';
import type {TimeoutError as TimedOutTimeoutError} from './timed-out.js';
Expand Down Expand Up @@ -261,3 +262,37 @@ export class AbortError extends RequestError {
}
}
}

/**
An error to be thrown when the response body does not match the [Standard Schema](https://standardschema.dev) validator passed to `.json(schema)`. Includes an `issues` property with the issues from the schema. Each issue has a `message` and an optional `path`.

It intentionally does not extend `RequestError`, because the request succeeded. The user-provided schema did not accept the data, so it has no `code`, `options`, `request`, `response` or `timings` property, and it is not passed to `beforeError` hooks.

@example
```
import got, {SchemaValidationError} from 'got';
import {z} from 'zod';

const userSchema = z.object({name: z.string()});

try {
const user = await got('https://example.com/user').json(userSchema);
console.log(user.name);
} catch (error) {
if (error instanceof SchemaValidationError) {
console.error(error.issues);
} else {
throw error;
}
}
```
*/
export class SchemaValidationError extends Error {
override name = 'SchemaValidationError';
readonly issues: readonly StandardSchemaV1Issue[];

constructor(issues: readonly StandardSchemaV1Issue[]) {
super('Response schema validation failed');
this.issues = issues;
}
}
2 changes: 2 additions & 0 deletions source/core/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3385,6 +3385,8 @@ export default class Options {

It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise.

`.json()` also accepts a [Standard Schema](https://standardschema.dev) validator, in which case the promise resolves with the output of the schema.

__Note__: When using streams, this option is ignored.

@example
Expand Down
1 change: 1 addition & 0 deletions source/core/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ export const parseBody = (response: Response, responseType: ResponseType, parseJ
}

if (responseType === 'json') {
// TODO: In the next major version, return `undefined` instead of `''` for an empty body, to match Ky. This affects `.json()`, `.json(schema)`, and `responseType: 'json'`. Also decide whether a custom `parseJson` should be called with `''` (Ky calls it).
if (rawBody.length === 0) {
return '';
}
Expand Down
56 changes: 56 additions & 0 deletions source/core/standard-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
The types of the [Standard Schema](https://standardschema.dev) specification (`v1`).

Copied from the specification so Got does not need a dependency for types only.
*/
export type StandardSchemaV1Issue = {
readonly message: string;
readonly path?: ReadonlyArray<PropertyKey | {readonly key: PropertyKey}> | undefined;
};

export type StandardSchemaV1SuccessResult<OutputType> = {
readonly value: OutputType;
readonly issues?: undefined;
};

export type StandardSchemaV1FailureResult = {
readonly issues: readonly StandardSchemaV1Issue[];
readonly value?: undefined;
};

export type StandardSchemaV1Result<OutputType> = StandardSchemaV1SuccessResult<OutputType> | StandardSchemaV1FailureResult;

export type StandardSchemaV1Types<InputType, OutputType> = {
readonly input: InputType;
readonly output: OutputType;
};

export type StandardSchemaV1Options = {
readonly libraryOptions?: Readonly<Record<string, unknown>> | undefined;
};

export type StandardSchemaV1<InputType = unknown, OutputType = InputType> = {
readonly '~standard': {
readonly version: 1;
readonly vendor: string;
readonly validate: (
value: unknown,
options?: StandardSchemaV1Options,
) => StandardSchemaV1Result<OutputType> | Promise<StandardSchemaV1Result<OutputType>>;
readonly types?: StandardSchemaV1Types<InputType, OutputType> | undefined;
};
};

/**
Infer the output type of a Standard Schema.
*/
export type StandardSchemaV1InferOutput<Schema extends StandardSchemaV1> = Schema['~standard'] extends {
readonly types: StandardSchemaV1Types<unknown, infer OutputType>;
}
? OutputType
: Extract<
Awaited<ReturnType<Schema['~standard']['validate']>>,
StandardSchemaV1SuccessResult<unknown>
> extends StandardSchemaV1SuccessResult<infer OutputType>
? OutputType
: unknown;
Loading
Loading