cryptgeon/frontend/src/lib/api.ts

75 lines
1.5 KiB
TypeScript
Raw Normal View History

2021-12-21 00:15:04 +01:00
export type NoteMeta = { type: 'text' | 'file' }
2021-05-02 03:08:30 +02:00
export type Note = {
contents: string
2021-12-21 00:15:04 +01:00
meta: NoteMeta
2021-05-02 03:08:30 +02:00
views?: number
expiration?: number
}
2021-05-03 12:21:51 +02:00
export type NoteInfo = {}
2021-12-21 00:15:04 +01:00
export type NotePublic = Pick<Note, 'contents' | 'meta'>
export type NoteCreate = Omit<Note, 'meta'> & { meta: string }
export type FileDTO = Pick<File, 'name' | 'size' | 'type'> & {
contents: string
}
2021-05-02 03:08:30 +02:00
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-12-22 13:10:08 +01:00
export 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-12-21 00:15:04 +01:00
const { meta, ...rest } = note
const body: NoteCreate = {
...rest,
meta: JSON.stringify(meta),
}
2021-05-07 14:09:26 +02:00
const data = await call({
2021-12-22 13:10:08 +01:00
url: 'notes/',
2021-05-02 03:08:30 +02:00
method: 'post',
2021-12-21 00:15:04 +01:00
body,
2021-05-02 03:08:30 +02:00
})
return data as { id: string }
}
2021-12-21 00:15:04 +01:00
export async function get(id: string): Promise<NotePublic> {
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',
})
2021-12-21 00:15:04 +01:00
const { contents, meta } = data
return {
contents,
meta: JSON.parse(meta) as NoteMeta,
}
2021-05-02 03:08:30 +02:00
}
2021-12-21 00:15:04 +01:00
export async function info(id: string): Promise<NoteInfo> {
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',
})
2021-12-21 00:15:04 +01:00
return data
2021-05-02 03:08:30 +02:00
}