Skip to content

Commit

Permalink
Add Typed Fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
ingalls committed May 6, 2024
1 parent 9f53d6e commit 141dcb6
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@

## Version History

### v4.7.0

- :rocket: Expose TypedFetch Interface

### v4.6.0

- :rocket: Update Alert API
Expand Down
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { FeatureCollection } from 'geojson';
import { Type, TSchema } from '@sinclair/typebox';
import moment from 'moment-timezone';
import jwt from 'jsonwebtoken';
export * from './src/fetch.js'

export interface Event {
type?: string
Expand Down
20 changes: 19 additions & 1 deletion package-lock.json

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

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,14 @@
"typescript-eslint": "^7.7.0"
},
"dependencies": {
"@openaddresses/batch-error": "^2.4.0",
"@sinclair/typebox": "^0.32.20",
"@types/geojson": "^7946.0.10",
"@types/jsonwebtoken": "^9.0.1",
"@types/minimist": "^1.2.5",
"jsonwebtoken": "^9.0.0",
"minimist": "^1.2.8",
"moment-timezone": "^0.5.45"
"moment-timezone": "^0.5.45",
"undici": "^6.15.0"
}
}
38 changes: 38 additions & 0 deletions src/fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import Err from '@openaddresses/batch-error';
import { Static, TSchema, TUnknown } from "@sinclair/typebox";
import { TypeCompiler } from "@sinclair/typebox/compiler";
import { fetch, Response } from 'undici';
import type { RequestInfo, RequestInit } from 'undici';

export class TypedResponse extends Response {
constructor(response: Response) {
super(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}

typed<T extends TSchema>(type: T): Promise<Static<T>>;

async typed<T extends TSchema = TUnknown>(type: T): Promise<Static<T>> {
const body = await this.json();

const typeChecker = TypeCompiler.Compile(type)
const result = typeChecker.Check(body);

if (result) return body;

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

throw new Err(500, null, `Internal Validation Error: ${JSON.stringify(firstError)}`);
}
}

export default async function(
input: RequestInfo,
init?: RequestInit
): Promise<TypedResponse> {
return new TypedResponse(await fetch(input, init));
}

0 comments on commit 141dcb6

Please sign in to comment.