calcom/server/createContext.ts
Alex Johansson 34300650e4
add tRPC (#614)
* add trpc

* trpc specific

* fix deps

* lint fix

* upgrade prisma

* nativeTypes

* nope, not needed

* fix app propviders

* Revert "upgrade prisma"

This reverts commit e6f2d2542a01ec82c80aa2fe367ae12c68ded1a5.

* rev

* up trpc

* simplify

* wip - bookings page with trpc

* bookings using trpc

* fix `Shell` props

* call it viewerRouter instead

* cleanuop

* ssg helper

* fix lint

* fix types

* skip

* add `useRedirectToLoginIfUnauthenticated`

* exhaustive-deps

* fix callbackUrl

* rewrite `/availability` using trpc

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2021-09-27 14:47:55 +00:00

68 lines
1.6 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-unused-vars */
import * as trpc from "@trpc/server";
import { Maybe } from "@trpc/server";
import * as trpcNext from "@trpc/server/adapters/next";
import { getSession, Session } from "@lib/auth";
import prisma from "@lib/prisma";
import { defaultAvatarSrc } from "@lib/profile";
async function getUserFromSession(session: Maybe<Session>) {
if (!session?.user?.id) {
return null;
}
const user = await prisma.user.findUnique({
where: {
id: session.user.id,
},
select: {
id: true,
username: true,
name: true,
email: true,
bio: true,
timeZone: true,
weekStart: true,
startTime: true,
endTime: true,
bufferTime: true,
theme: true,
createdDate: true,
hideBranding: true,
avatar: true,
},
});
// some hacks to make sure `username` and `email` are never inferred as `null`
if (!user) {
return null;
}
const { email, username } = user;
if (!username || !email) {
return null;
}
const avatar = user.avatar || defaultAvatarSrc({ email });
return {
...user,
avatar,
email,
username,
};
}
/**
* Creates context for an incoming request
* @link https://trpc.io/docs/context
*/
export const createContext = async ({ req, res }: trpcNext.CreateNextContextOptions) => {
// for API-response caching see https://trpc.io/docs/caching
const session = await getSession({ req });
return {
prisma,
session,
user: await getUserFromSession(session),
};
};
export type Context = trpc.inferAsyncReturnType<typeof createContext>;