cryptgeon/client/src/lib/api.ts

52 lines
1.0 KiB
TypeScript
Raw Normal View History

2021-05-02 12:31:32 +02:00
import { dev } from '$app/env'
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-05-08 10:16:05 +02:00
const base = dev ? 'http://localhost:5000/api/' : '/api/'
2021-05-07 14:09:26 +02:00
async function call(options: CallOptions) {
return fetch(base + options.url, {
method: options.method,
body: options.body === undefined ? undefined : JSON.stringify(options.body),
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
}).then((r) => r.json())
}
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
}