added playground and userroute

This commit is contained in:
2024-04-19 13:01:58 +07:00
parent a90529f258
commit a3f61b35c1
13 changed files with 1110 additions and 80 deletions

59
src/trpc.ts Normal file
View File

@@ -0,0 +1,59 @@
import { initTRPC } from "@trpc/server";
import type { CreateHTTPContextOptions } from "@trpc/server/adapters/standalone";
import { db } from "./db";
const t = initTRPC.context<Context>().create();
export const router = t.router;
export const publicProcedure = t.procedure;
export const protectedProcedure = t.procedure.use(async (opts) => {
const { ctx } = opts;
if (ctx.user === undefined) {
throw new Error("Unauthorized");
} else {
return opts.next({
ctx: {
...ctx,
user: ctx.user,
},
});
}
});
export const verifiedPhone = t.procedure.use(async (opts) => {
const { ctx } = opts;
if (ctx.phone === undefined) {
throw new Error("Unauthorized");
} else {
return opts.next({
ctx: {
phone: ctx.phone,
},
});
}
});
type Context = Awaited<ReturnType<typeof createContext>>;
export const createContext = async (opts: CreateHTTPContextOptions) => {
const authorizationHeader = opts.req.headers.authorization || "";
const bearerToken = authorizationHeader.split(" ")[1];
const phone = verifyToken(bearerToken);
if (phone !== null) {
let user = await db.query.user.findFirst({
where: (user, { eq }) => eq(user.phone, phone),
});
return {
phone,
user: user,
};
} else {
return {
phone: undefined,
user: undefined,
};
}
};
function verifyToken(token: string): string | null {
//TODO: Implement token verification
return "08999";
}