Skip to content
Open
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
7 changes: 2 additions & 5 deletions example/1.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { Type } from "@sinclair/typebox";
import { TypeCompiler } from "@sinclair/typebox/compiler";
import { fetch } from "../src";

const ResponseType = TypeCompiler.Compile(
Type.Object({
const ResponseType = Type.Object({
id: Type.Number(),
userId: Type.Number(),
title: Type.String(),
})
);
})

async function main() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
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.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@erfanium/fetch-typebox",
"version": "0.2.2",
"version": "0.3.1",
"description": "",
"main": "index.js",
"types": "index.d.ts",
Expand Down
Binary file modified screenshots/1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 7 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Static, TSchema, TUnknown } from "@sinclair/typebox";
import { TypeCheck } from "@sinclair/typebox/compiler";
import { Value } from '@sinclair/typebox/value'

export class ResponseValidationError extends Error {}

Expand All @@ -13,23 +13,20 @@ export class TypeBoxResponse extends Response {
}

json(): Promise<unknown>;
json<T extends TSchema>(typeChecker: TypeCheck<T>): Promise<Static<T>>;
json<T extends TSchema>(schema: T): Promise<Static<T>>;
async json<T extends TSchema = TUnknown>(
typeChecker?: TypeCheck<T>
schema?: T
): Promise<Static<T>> {
if (!typeChecker) return super.json();
if (!schema) return super.json();
const body = await super.json();
const result = typeChecker.Check(body);
const result = Value.Check(schema, body);
if (result) return body;

const errors = typeChecker.Errors(body);
const errors = Value.Errors(schema, body);
const firstError = errors.First();

throw new ResponseValidationError(
`ResponseValidationError ${firstError?.message}. path: ${firstError?.path} value: ${firstError?.value}`,
{
cause: firstError,
}
`ResponseValidationError ${firstError?.message}. path: ${firstError?.path} value: ${firstError?.value}`
);
}
}
Expand Down