budibase/examples/nextjs-api-sales/pages/api/sales.ts

115 lines
3.0 KiB
TypeScript
Raw Normal View History

import getConfig from "next/config"
2022-03-08 21:17:07 +01:00
import {App, AppSearch, Table, TableSearch} from "../../definitions"
const { serverRuntimeConfig } = getConfig()
const apiKey = serverRuntimeConfig["apiKey"]
const appName = serverRuntimeConfig["appName"]
const host = serverRuntimeConfig["host"]
2022-03-08 21:17:07 +01:00
let APP: App | null = null
let TABLES: { [key: string]: Table } = {}
async function makeCall(method: string, url: string, opts?: { body?: any, appId?: string }): Promise<any> {
const fetchOpts: any = {
method,
headers: {
"x-budibase-api-key": apiKey,
}
}
if (opts?.appId) {
fetchOpts.headers["x-budibase-app-id"] = opts.appId
}
if (opts?.body) {
2022-03-08 21:17:07 +01:00
fetchOpts.body = typeof opts.body !== "string" ? JSON.stringify(opts.body) : opts.body
fetchOpts.headers["Content-Type"] = "application/json"
}
2022-03-08 21:17:07 +01:00
const finalUrl = `${host}/api/public/v1/${url}`
const response = await fetch(finalUrl, fetchOpts)
if (response.ok) {
return response.json()
} else {
2022-03-08 21:17:07 +01:00
const error = await response.text()
console.error("Budibase server error - ", error)
throw new Error(error)
}
}
async function getApp(): Promise<App> {
2022-03-08 21:17:07 +01:00
if (APP) {
return APP
}
const apps: AppSearch = await makeCall("post", "applications/search", {
body: {
name: appName,
}
})
const app = apps.data.find((app: App) => app.name === appName)
if (!app) {
throw new Error("Could not find app, please make sure app name in config is correct.")
}
2022-03-08 21:17:07 +01:00
APP = app
return app
}
2022-03-08 21:17:07 +01:00
async function findTable(appId: string, tableName: string): Promise<Table> {
if (TABLES[tableName]) {
return TABLES[tableName]
}
const tables: TableSearch = await makeCall("post", "tables/search", {
body: {
name: tableName,
},
appId,
})
const table = tables.data.find((table: Table) => table.name === tableName)
if (!table) {
throw new Error("Could not find table, please make sure your app is configured with the Postgres datasource correctly.")
}
TABLES[tableName] = table
return table
}
async function getSales(req: any) {
2022-03-08 21:17:07 +01:00
const { page } = req.query
const { _id: appId } = await getApp()
2022-03-08 21:17:07 +01:00
const table = await findTable(appId, "sales")
return await makeCall("post", `tables/${table._id}/rows/search`, {
appId,
body: {
limit: 10,
sort: {
type: "string",
order: "ascending",
column: "sale_id",
},
paginate: true,
bookmark: parseInt(page),
}
})
}
async function saveSale(req: any) {
const { _id: appId } = await getApp()
2022-03-08 21:17:07 +01:00
const table = await findTable(appId, "sales")
return await makeCall("post", `tables/${table._id}/rows`, {
body: req.body,
appId,
})
}
export default async function handler(req: any, res: any) {
let response: any = {}
2022-03-08 21:17:07 +01:00
try {
if (req.method === "POST") {
response = await saveSale(req)
} else if (req.method === "GET") {
response = await getSales(req)
} else {
res.status(404)
return
}
res.status(200).json(response)
} catch (err: any) {
res.status(400).send(err)
}
}