98 lines
2.6 KiB
TypeScript
98 lines
2.6 KiB
TypeScript
import type {
|
|
BUN_SQLITE_WGUI_USER_TYPES,
|
|
BUN_SQLITE_WGUI_USERS,
|
|
} from "@/db/types/db";
|
|
import { AppData } from "@/src/data/app-data";
|
|
import grabUsers from "@/src/functions/backend/db/users/grab-users";
|
|
import type { ApiReqParams, TableType } from "@/src/types";
|
|
import BunSQLite from "@moduletrace/bun-sqlite";
|
|
import type {
|
|
APIResponseObject,
|
|
BunextAPIRouteHandler,
|
|
} from "@moduletrace/bunext/types";
|
|
|
|
export const handler: BunextAPIRouteHandler<
|
|
APIResponseObject<BUN_SQLITE_WGUI_USERS>
|
|
> = async (ctx) => {
|
|
try {
|
|
const body = ctx.body as ApiReqParams;
|
|
|
|
const users_res = await grabUsers({
|
|
query: {
|
|
sql_query: {
|
|
limit: 1,
|
|
},
|
|
},
|
|
});
|
|
|
|
if (users_res.singleRes?.id) {
|
|
return {
|
|
success: false,
|
|
};
|
|
}
|
|
|
|
const final_insert_data = await Promise.all(
|
|
body?.insert_data?.map(async (data) => {
|
|
if (!data.password) {
|
|
throw new Error(
|
|
`Password is required to create the first user.`,
|
|
);
|
|
}
|
|
|
|
return {
|
|
...data,
|
|
password: await Bun.password.hash(data.password, {
|
|
algorithm: "bcrypt",
|
|
cost: AppData["HashCost"],
|
|
}),
|
|
id: 1,
|
|
};
|
|
}) || [],
|
|
);
|
|
|
|
const POST = await BunSQLite.insert<BUN_SQLITE_WGUI_USERS, TableType>({
|
|
table: "users",
|
|
data: final_insert_data,
|
|
});
|
|
|
|
const new_users_res = await grabUsers({
|
|
query: {
|
|
sql_query: {
|
|
limit: 1,
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!new_users_res.singleRes?.id) {
|
|
throw new Error(
|
|
`Couldn't find newly created user record! Try again.`,
|
|
);
|
|
}
|
|
|
|
const add_super_admin_user_types = await BunSQLite.insert<
|
|
BUN_SQLITE_WGUI_USER_TYPES,
|
|
TableType
|
|
>({
|
|
table: "user_types",
|
|
data: [
|
|
{
|
|
user_type: "super_admin",
|
|
user_id: new_users_res.singleRes.id,
|
|
},
|
|
],
|
|
});
|
|
|
|
console.log("add_super_admin_user_types", add_super_admin_user_types);
|
|
|
|
return {
|
|
...POST,
|
|
singleRes: new_users_res.singleRes,
|
|
};
|
|
} catch (error: any) {
|
|
return {
|
|
success: false,
|
|
msg: error.message,
|
|
};
|
|
}
|
|
};
|