Skip to content

Instantly share code, notes, and snippets.

@u007
Created January 30, 2024 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u007/1cc5cd5120dd47e1c2fac3a7ebc945a1 to your computer and use it in GitHub Desktop.
Save u007/1cc5cd5120dd47e1c2fac3a7ebc945a1 to your computer and use it in GitHub Desktop.
trpc on cloud function
import { inferAsyncReturnType, initTRPC, TRPCError } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
import express from 'express';
import dotenv from 'dotenv';
import { appRouter } from './router/server';
import cors, { CorsOptions } from 'cors';
import jsonwebtoken from 'jsonwebtoken';
// import * as functions from 'firebase-functions';
import type { HttpFunction } from '@google-cloud/functions-framework';
const { decode } = jsonwebtoken;
import { createExpressMiddleware } from '@trpc/server/adapters/express';
dotenv.config();
const port = process.env.PORT || '4000';
type RequestUser = {
_id: string;
firstName: string;
lastName: string;
displayName: string;
email: string;
}
// created for each request
const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions): { user : RequestUser | null } => {
const auth = req.header('authorization') || '';
const token = auth?.replace('Bearer ', '');
// console.log('auth', auth);
if (token) {
const res = decode(token) as any;
// console.log('jwt', res.user_data);
const user = res?.user_data;
return {
user: {
...user,
}
}
}
return {
user: null,
}
}// no context
export type Context = inferAsyncReturnType<typeof createContext>;
const corsOptions: CorsOptions = {
allowedHeaders: ['Content-Type', 'Authorization'],
origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
const allowedOrigins = ['http://localhost', /\.xyz\.com$/];
if (!origin || allowedOrigins.some(o => o instanceof RegExp ? o.test(origin) : o === origin)) {
callback(null, true);
} else {
console.log('origin error', origin);
callback(new Error('Not allowed by CORS'), false);
}
},
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
};
export const setup = () => {
const app = express();
app.use('/',
cors(corsOptions),
createExpressMiddleware({
router: appRouter,
createContext,
}));
return app;
};
export const trpcFunction: HttpFunction = (req, res) => {
setup()(req, res);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment