All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m6s
95 lines
2.4 KiB
TypeScript
95 lines
2.4 KiB
TypeScript
import type { APIRoute } from "astro";
|
|
import { db } from "../../../db";
|
|
import { clients, members } from "../../../db/schema";
|
|
import { eq } from "drizzle-orm";
|
|
import { nanoid } from "nanoid";
|
|
|
|
export const POST: APIRoute = async ({ request, locals, redirect }) => {
|
|
const user = locals.user;
|
|
if (!user) {
|
|
return new Response("Unauthorized", { status: 401 });
|
|
}
|
|
|
|
let name: string | undefined;
|
|
let email: string | undefined;
|
|
let phone: string | undefined;
|
|
let street: string | undefined;
|
|
let city: string | undefined;
|
|
let state: string | undefined;
|
|
let zip: string | undefined;
|
|
let country: string | undefined;
|
|
|
|
if (request.headers.get("Content-Type")?.includes("application/json")) {
|
|
const body = await request.json();
|
|
name = body.name;
|
|
email = body.email;
|
|
phone = body.phone;
|
|
street = body.street;
|
|
city = body.city;
|
|
state = body.state;
|
|
zip = body.zip;
|
|
country = body.country;
|
|
} else {
|
|
const formData = await request.formData();
|
|
name = formData.get("name")?.toString();
|
|
email = formData.get("email")?.toString();
|
|
phone = formData.get("phone")?.toString();
|
|
street = formData.get("street")?.toString();
|
|
city = formData.get("city")?.toString();
|
|
state = formData.get("state")?.toString();
|
|
zip = formData.get("zip")?.toString();
|
|
country = formData.get("country")?.toString();
|
|
}
|
|
|
|
if (!name) {
|
|
return new Response("Name is required", { status: 400 });
|
|
}
|
|
|
|
const userOrg = await db
|
|
.select()
|
|
.from(members)
|
|
.where(eq(members.userId, user.id))
|
|
.get();
|
|
|
|
if (!userOrg) {
|
|
return new Response("No organization found", { status: 400 });
|
|
}
|
|
|
|
const id = nanoid();
|
|
|
|
await db.insert(clients).values({
|
|
id,
|
|
organizationId: userOrg.organizationId,
|
|
name,
|
|
email: email || null,
|
|
phone: phone || null,
|
|
street: street || null,
|
|
city: city || null,
|
|
state: state || null,
|
|
zip: zip || null,
|
|
country: country || null,
|
|
});
|
|
|
|
if (locals.scopes) {
|
|
return new Response(
|
|
JSON.stringify({
|
|
id,
|
|
name,
|
|
email: email || null,
|
|
phone: phone || null,
|
|
street: street || null,
|
|
city: city || null,
|
|
state: state || null,
|
|
zip: zip || null,
|
|
country: country || null,
|
|
}),
|
|
{
|
|
status: 201,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
}
|
|
|
|
return redirect("/dashboard/clients");
|
|
};
|