66 lines
1.7 KiB
TypeScript
66 lines
1.7 KiB
TypeScript
import type { Delta } from "quill";
|
|
|
|
export interface Entry {
|
|
date: string,
|
|
location: { lat: number, long: number } | null,
|
|
content: Delta
|
|
}
|
|
|
|
// ty https://stackoverflow.com/questions/35940290
|
|
function dataURLtoFile(dataurl: string, filename: string) {
|
|
var arr = dataurl.split(','),
|
|
mime = arr[0].match(/:(.*?);/)[1],
|
|
bstr = atob(arr[arr.length - 1]),
|
|
n = bstr.length,
|
|
u8arr = new Uint8Array(n);
|
|
while(n--){
|
|
u8arr[n] = bstr.charCodeAt(n);
|
|
}
|
|
return new File([u8arr], filename, {type:mime});
|
|
}
|
|
|
|
async function uploadImage(b64: string) {
|
|
const data = new FormData()
|
|
|
|
// unable to tell from the b64 whether it's a jpg or png but defaulting to jpg seems to work fine enough
|
|
const file = dataURLtoFile(b64, 'image.jpg')
|
|
data.append('image', file)
|
|
|
|
const r = await fetch('/api/image', {
|
|
method: 'POST',
|
|
body: data
|
|
})
|
|
|
|
const url = (await r.json()).url
|
|
return url
|
|
}
|
|
|
|
async function uploadAllImages(delta: Delta) {
|
|
let newDelta = delta
|
|
|
|
for (const val of newDelta.ops) {
|
|
if (val.insert?.image != null) {
|
|
const imgUrl = await uploadImage(val.insert!.image)
|
|
val.insert!.image = imgUrl
|
|
}
|
|
}
|
|
|
|
return newDelta
|
|
}
|
|
|
|
export async function uploadEntry(entry: Entry) {
|
|
// first upload all the images seperately
|
|
const delta = await uploadAllImages(entry.content)
|
|
|
|
const finalEntry: Entry = {
|
|
date: entry.date,
|
|
location: entry.location,
|
|
content: delta
|
|
}
|
|
|
|
const r = await fetch('/api/entry/new', {
|
|
method: 'POST',
|
|
headers: {'content-type': 'application/json'},
|
|
body: JSON.stringify(finalEntry)
|
|
})
|
|
} |