cryptgeon/client/src/lib/api.ts

58 lines
1.1 KiB
TypeScript
Raw Normal View History

2021-05-02 03:08:30 +02:00
export type Note = {
contents: string
views?: number
expiration?: number
}
2021-05-03 12:21:51 +02:00
export type NoteInfo = {}
2021-05-02 03:08:30 +02:00
export type NotePublic = Pick<Note, 'contents'>
2021-05-07 14:09:26 +02:00
type CallOptions = {
url: string
method: string
body?: any
}
2021-12-20 18:14:59 +01:00
2021-12-20 18:22:10 +01:00
export class PayloadToLargeError extends Error {}
2021-05-07 14:09:26 +02:00
async function call(options: CallOptions) {
2021-12-20 18:22:10 +01:00
const response = await fetch('/api/' + options.url, {
2021-05-07 14:09:26 +02:00
method: options.method,
body: options.body === undefined ? undefined : JSON.stringify(options.body),
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
2021-12-20 18:22:10 +01:00
})
if (!response.ok) {
if (response.status === 413) throw new PayloadToLargeError()
else throw new Error('API call failed')
}
return response.json()
2021-05-07 14:09:26 +02:00
}
2021-05-02 03:08:30 +02:00
export async function create(note: Note) {
2021-05-07 14:09:26 +02:00
const data = await call({
2021-05-08 10:16:05 +02:00
url: 'notes',
2021-05-02 03:08:30 +02:00
method: 'post',
2021-05-07 14:09:26 +02:00
body: note,
2021-05-02 03:08:30 +02:00
})
return data as { id: string }
}
export async function get(id: string) {
2021-05-07 14:09:26 +02:00
const data = await call({
2021-05-08 10:16:05 +02:00
url: `notes/${id}`,
2021-05-02 03:08:30 +02:00
method: 'delete',
})
return data as NotePublic
}
export async function info(id: string) {
2021-05-07 14:09:26 +02:00
const data = await call({
2021-05-08 10:16:05 +02:00
url: `notes/${id}`,
2021-05-02 03:08:30 +02:00
method: 'get',
})
return data as NoteInfo
}