1
0
mirror of https://github.com/uetchy/namae.git synced 2025-03-17 04:30:31 +09:00
namae/api/util/http.ts

36 lines
757 B
TypeScript
Raw Normal View History

2019-09-17 14:30:33 +09:00
import nodeFetch from 'isomorphic-unfetch';
2019-08-30 16:40:22 +09:00
export type HttpMethod =
| 'GET'
| 'POST'
| 'PUT'
| 'DELETE'
| 'HEAD'
| 'PATCH'
| 'CONNECT'
2019-09-17 14:30:33 +09:00
| 'TRACE';
2019-08-30 16:40:22 +09:00
2019-09-17 14:30:33 +09:00
export interface NowRequest<T = {query: string}> {
query: T;
2019-08-30 16:40:22 +09:00
}
export interface NowResponse {
2019-09-17 14:30:33 +09:00
setHeader: (label: string, body: string) => void;
json: (obj: object) => void;
status: (code: number) => NowResponse;
length: number;
2019-08-30 16:40:22 +09:00
}
export function fetch(url: string, method: HttpMethod = 'HEAD') {
2019-09-17 14:30:33 +09:00
return nodeFetch(url, {method: method});
2019-08-30 16:40:22 +09:00
}
export function send(res: NowResponse, data: object) {
2019-09-17 14:30:33 +09:00
res.setHeader('Cache-Control', 's-maxage=86400');
res.json(data);
2019-08-30 16:40:22 +09:00
}
export function sendError(res: NowResponse, error: Error) {
2019-09-17 14:30:33 +09:00
res.status(400).json({error: error.message});
2019-08-30 16:40:22 +09:00
}