feat: get collection from env

This commit is contained in:
hasitotabla 2025-01-02 22:35:47 +01:00
parent fb7740dae0
commit eda85a3292
2 changed files with 187 additions and 187 deletions

View file

@ -1,61 +1,61 @@
import pb from "@/lib/pocketbase";
const { EMAIL, PASSWORD } = process.env;
const { EMAIL, PASSWORD, COLLECTION = "budgetable" } = process.env;
async function authenticateSuperuser() {
if (!EMAIL || !PASSWORD) {
throw new Error("Environment variables EMAIL and PASSWORD must be set");
}
if (!pb.authStore.isValid) {
await pb.collection("_superusers").authWithPassword(EMAIL, PASSWORD);
}
if (!EMAIL || !PASSWORD) {
throw new Error("Environment variables EMAIL and PASSWORD must be set");
}
if (!pb.authStore.isValid) {
await pb.collection("_superusers").authWithPassword(EMAIL, PASSWORD);
}
}
export async function GET() {
try {
await authenticateSuperuser();
const records = await pb.collection("budgetable").getFullList();
return Response.json(records, {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error fetching data:", error);
return Response.json(
{
error: {
message: "Failed to fetch data",
},
},
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
try {
await authenticateSuperuser();
const records = await pb.collection(COLLECTION).getFullList();
return Response.json(records, {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error fetching data:", error);
return Response.json(
{
error: {
message: "Failed to fetch data",
},
},
{
status: 500,
headers: { "Content-Type": "application/json" },
}
);
}
}
export async function POST(req: Request) {
try {
await authenticateSuperuser();
const data = await req.json();
const record = await pb.collection("budgetable").create(data);
return Response.json(record, {
status: 201,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error adding data:", error);
return Response.json(
{
error: {
message: "Failed to add data",
},
},
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
try {
await authenticateSuperuser();
const data = await req.json();
const record = await pb.collection(COLLECTION).create(data);
return Response.json(record, {
status: 201,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error adding data:", error);
return Response.json(
{
error: {
message: "Failed to add data",
},
},
{
status: 500,
headers: { "Content-Type": "application/json" },
}
);
}
}