nim/src/api.ts
2025-06-10 22:10:01 +08:00

78 lines
2 KiB
TypeScript

import { z } from 'zod/v4'
let rooturl = 'http://172.16.20.145:3000'
type Inputs = {
content: string
signing?: string
files?: FileList
}
export const FetchPost_t = z.array(
z.object({
id: z.number(),
content: z.string(),
signing: z.nullable(z.string()),
post_at: z.coerce.date(),
heart: z.number(),
igid: z.nullable(z.string()),
enclosure: z.array(z.nullable(z.string())),
})
)
export const Post = async (post_form: Inputs) => {
// Delete Blank Item
let processed_form = new FormData()
processed_form.set('content', post_form.content)
if (post_form.files && post_form.files.length > 0) {
for (const file of post_form.files) {
processed_form.append('files', file)
}
}
if (post_form.signing && post_form.signing.length > 0) {
processed_form.append('signing', post_form.signing)
}
let resp = await fetch(rooturl + '/api/post', {
method: 'POST',
body: processed_form,
})
let parsed = await resp.json()
// geolocation
// let location: Promise<GeolocationCoordinates> = new Promise((resolv, rej) => {
// navigator.geolocation.getCurrentPosition(
// (pos) => {
// resolv(pos.coords)
// },
// (err) => {
// rej(err)
// },
// {}
// )
// })
// try {
// let coord = await location
// processed_form.append('location', `${coord?.latitude},${coord?.longitude}`)
// } catch (error) {
// console.log('Failed to get location')
// }
//
return parsed as { id: number; hash: string }
}
export const DeletePost = async (id: number, hash: string) => {
let x = await fetch(`${rooturl}/api/post?post=${id}&hash=${hash}`, {
method: 'DELETE',
})
return x.status == 200
}
export const FetchPost = async (cursor?: number) => {
let resp = await fetch(
`${rooturl}/api/post${cursor ? '?cursor=' + cursor.toString() : ''}`
)
if (resp.status == 200) {
return FetchPost_t.parse(await resp.json())
}
return null
}
export const MediaPathTrc = (path: string) => {
return rooturl + '/static/' + path
}