added playground and userroute
This commit is contained in:
59
src/trpc.ts
Normal file
59
src/trpc.ts
Normal 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";
|
||||
}
|
||||
Reference in New Issue
Block a user