Skip to content

Commit

Permalink
0.0.4 - use a proper error class
Browse files Browse the repository at this point in the history
  • Loading branch information
williamhorning committed Dec 15, 2024
1 parent c0679de commit f05fc01
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 64 deletions.
1 change: 1 addition & 0 deletions packages/revolt-api-types/scripts/typegen.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// deno-lint-ignore no-external-import
import openapi from 'npm:[email protected]';

const schema_url = 'https://api.revolt.chat/openapi.json';
Expand Down
2 changes: 1 addition & 1 deletion packages/rvapi/deno.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@jersey/rvapi",
"version": "0.0.3",
"version": "0.0.4",
"exports": "./src/mod.ts",
"imports": {
"@denosaurs/event": "jsr:@denosaurs/event@^2.0.2",
Expand Down
63 changes: 4 additions & 59 deletions packages/rvapi/src/delta/mod.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,7 @@
import { queryParams, type routes } from '@jersey/revolt-api-types';
import { path_name } from './path_name.ts';

/**
* create a request function
* @param base_url the base url to use
* @param headers the headers to use
* @returns a request function
* Delta is the Revolt API requestor
* @module
*/
export function createRequest(
base_url: string,
headers: Record<string, string>,
): request {
return async (method, path, params) => {
const query = new URLSearchParams();
const body = {} as Record<string, unknown>;
const named = path_name(path);

if (named && params && typeof params === 'object') {
const route = queryParams[named as keyof typeof queryParams];
const allowed_query = (route as Record<typeof method, string[]>)[method];
for (const param of Object.keys(params)) {
if (allowed_query.includes(param)) {
query.append(param, (params as Record<string, string>)[param]);
} else {
body[param] = (params as Record<string, string>)[param];
}
}
}

const req_body = ['head', 'get'].includes(method)
? undefined
: JSON.stringify(body);

const res = await fetch(`${base_url}${path}?${query.toString()}`, {
method,
headers,
body: req_body,
});

if (res.ok) {
return await res.json();
} else {
throw new Error(`Request failed with status ${res.status}`, {
cause: res,
});
}
};
}

/**
* make a request against the revolt api
*/
export type request = <
method extends routes['method'],
path extends (routes & { method: method })['path'],
route extends (routes & { method: method; path: path }),
>(
method: method,
path: path,
params: route['params'],
) => Promise<Exclude<route['response'], string>>;
export * from './request.ts';
export * from './types.ts';
52 changes: 52 additions & 0 deletions packages/rvapi/src/delta/request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { queryParams } from '@jersey/revolt-api-types';
import { path_name } from './path_name.ts';
import { type request, RequestError } from './types.ts';

/**
* create a request function
* @param base_url the base url to use
* @param headers the headers to use
* @returns a request function
*/
export function createRequest(
base_url: string,
headers: Record<string, string>,
): request {
return async (method, path, params) => {
const query = new URLSearchParams();
const body = {} as Record<string, unknown>;
const named = path_name(path);

if (named && params && typeof params === 'object') {
const route = queryParams[named as keyof typeof queryParams];
const allowed_query = (route as Record<typeof method, string[]>)[method];
for (const param of Object.keys(params)) {
if (allowed_query.includes(param)) {
query.append(param, (params as Record<string, string>)[param]);
} else {
body[param] = (params as Record<string, string>)[param];
}
}
}

const req_body = ['head', 'get', 'HEAD', 'GET'].includes(method)
? undefined
: JSON.stringify(body);

const res = await fetch(`${base_url}${path}?${query.toString()}`, {
method,
headers,
body: req_body,
});

if (res.ok) {
try {
return await res.json();
} catch (e) {
throw e;
}
} else {
throw new RequestError(method, path, params, res);
}
};
}
33 changes: 33 additions & 0 deletions packages/rvapi/src/delta/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { routes } from '@jersey/revolt-api-types';

/**
* make a request against the revolt api
*/
export type request = <
method extends routes['method'],
path extends (routes & { method: method })['path'],
route extends (routes & { method: method; path: path }),
>(
method: method,
path: path,
params: route['params'],
) => Promise<Exclude<route['response'], string>>;

/** an error with a request to the api */
export class RequestError extends Error {
/** the cause of the error from the api */
override cause: Response;
method: string;
path: string;
params: unknown;

/** create an error */
constructor(method: string, path: string, params: unknown, cause: Response) {
super(`Failed to ${method} ${path}: ${cause.status}`);
this.name = 'RequestError';
this.cause = cause;
this.method = method;
this.path = path;
this.params = params;
}
}
4 changes: 2 additions & 2 deletions packages/rvapi/src/media/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class MediaServices {
const proxy_url = `https://${this.january.url}/proxy?url=${
encodeURIComponent(url)
}`;
const resp = await fetch(proxy_url, { method: 'GET' });
const resp = await fetch(proxy_url);
if (!resp.ok || resp.headers.get('Content-Type') === 'application/json') {
throw new MediaError('get proxy', (await resp.json()).type);
}
Expand Down Expand Up @@ -78,7 +78,7 @@ export class MediaServices {
download_url.searchParams.set('width', options.width.toString());
}

const resp = await fetch(download_url.toString(), { method: 'GET' });
const resp = await fetch(download_url);

if (!resp.ok) {
throw new MediaError('download file', (await resp.json()).type);
Expand Down
4 changes: 2 additions & 2 deletions packages/rvapi/src/media/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ export interface download_options {
/** an error with a request to january or autumn */
export class MediaError extends Error {
/** the cause of the error from the api */
cause: string;
override cause: string;

/** create an error */
constructor(action: string, cause: string) {
super(`Failed to ${action}: ${cause}`);
this.name = 'JanuaryError';
this.name = 'MediaError';
this.cause = cause;
}
}

0 comments on commit f05fc01

Please sign in to comment.