Skip to content

Instantly share code, notes, and snippets.

@dipeshhkc
Last active December 23, 2021 13:18
Show Gist options
  • Save dipeshhkc/a22ace27c95a63c77914da0ef2fb1a6d to your computer and use it in GitHub Desktop.
Save dipeshhkc/a22ace27c95a63c77914da0ef2fb1a6d to your computer and use it in GitHub Desktop.
import { ActionFunction, json, redirect } from "remix";
import { db, enforcer } from "~/utils/db.server";
import { AuthActionData } from "~/types/auth";
import { authSchema } from "~/validations";
import { TeamMemberRoles } from "~/types/team";
const badRequest = (data: AuthActionData) => json(data, { status: 400 });
export const action: ActionFunction = async ({ request }) => {
const form = await request.formData();
const user_id = form.get("user_id");
const email = form.get("email");
if (typeof user_id !== "string" || typeof email !== "string") {
return badRequest({
formError: `Form not submitted correctly.`,
});
}
//validation
const fieldErrors = { user_id: "", email: "" };
try {
await authSchema.validate(
{
user_id,
email,
},
{ abortEarly: false }
);
} catch (err) {
err.inner.forEach((error) => {
if (error.path) {
fieldErrors[error.path] = error.message;
}
});
}
const fields = { user_id, email };
if (Object.values(fieldErrors).some(Boolean)) {
return badRequest({ fieldErrors, fields });
}
//success case
try {
//add user on db
const user = await db.user.create({
data: {
user_id: fields.user_id,
email: fields.email,
ownTeams: {
create: {
name: `Personal Team`,
},
},
},
include: {
ownTeams: true,
},
});
enforcer.addPolicy(
"g",
String(user.id),
TeamMemberRoles.ADMIN,
String(user.ownTeams[0].id)
);
} catch (error) {
return badRequest({
formError: error.message,
});
}
return redirect("/auth/login");
};
//call
fetcher.submit(
{ user_id: user.id, email: user.email },
{ action: "/api/auth/user", method: "post" }
);
const isLoadingState =
fetcher.state === "submitting" || (fetcher.state != "loading" && isLoading);
const formError = fetcher.data?.formError || errMsg;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment