71 lines
2.2 KiB
TypeScript
71 lines
2.2 KiB
TypeScript
import Pocketbase, { type RecordListOptions } from "pocketbase"
|
|
import {
|
|
type Recipe,
|
|
type Ingredient,
|
|
type Step,
|
|
type Tag,
|
|
Collection
|
|
} from './schema'
|
|
|
|
class APIClient {
|
|
client: Pocketbase
|
|
|
|
constructor() {
|
|
this.client = new Pocketbase("http://localhost:4321")
|
|
this.client.autoCancellation(false)
|
|
}
|
|
|
|
async getRecipesPage(page: number, perPage: number = 30, options: RecordListOptions) {
|
|
return await this.client.collection<Recipe>(Collection.RECIPES).getList(page, perPage, options)
|
|
}
|
|
|
|
async getAllRecipes() {
|
|
return await this.client.collection<Recipe>(Collection.RECIPES).getFullList({ expand: 'ingredients,tags,steps,images,steps.ingredients' })
|
|
}
|
|
|
|
async getRecipe(id: string) {
|
|
return await this.client.collection<Recipe>(Collection.RECIPES).getOne(id, { expand: 'ingredients,tags,steps,images,steps.ingredients' })
|
|
}
|
|
|
|
// IMAGE
|
|
async getImageURL(imgID: string, relative: boolean = true) {
|
|
const record = await this.client.collection(Collection.IMAGES).getOne(imgID)
|
|
const res = this.client.files.getURL(record, record.image)
|
|
return relative ? res.substring(21) : res
|
|
}
|
|
|
|
async getRecipeImages(recipeID: string) {
|
|
const re = await this.getRecipe(recipeID)
|
|
const imgIDs = re.images ?? []
|
|
|
|
const urls = Promise.all(
|
|
imgIDs.map(img => this.getImageURL(img))
|
|
)
|
|
return urls
|
|
}
|
|
|
|
async getAllTags() {
|
|
return await this.client.collection<Tag>(Collection.TAGS).getFullList()
|
|
}
|
|
|
|
async getTag(name: string) {
|
|
return await this.client.collection<Tag>(Collection.TAGS).getList(1, 50, { filter: `name = '${name}'` })
|
|
}
|
|
|
|
async getRecipesOfTag(tagName: string) {
|
|
// get the tag id first
|
|
const tagResult = await this.getTag(tagName)
|
|
if (tagResult.items.length === 0) {
|
|
return []
|
|
}
|
|
const tag = tagResult.items[0]
|
|
|
|
return await this.client.collection<Recipe>(Collection.RECIPES).getFullList({
|
|
filter: `tags ~ '${tag.id}'`,
|
|
expand: 'ingredients,tags,steps,images,steps.ingredients'
|
|
})
|
|
}
|
|
|
|
}
|
|
const client = new APIClient()
|
|
export default client; |