export async function createContext({ req, res }: CreateFastifyContextOptions) {
async function getUser() {
try {
const apiKey = req.headers['x-api-key']
if (apiKey) {
if (typeof apiKey !== 'string') {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid API key' })
}
const isValid = await validateApiKey(apiKey)
return {
user: null,
isAuthorized: isValid
}
} else {
await req.jwtVerify()
const em = orm.em.fork()
const user = await em.findOne(User, { _id: new ObjectId(req.user.id) })
if (!user) return null
const u = wrap(user).toPOJO()
return {
user: u,
isAuthorized: true
}
}
} catch (err) {
console.log('Error getting user from header or cookie', err)
return null
}
}
const user = await getUser()
return {
req,
res,
user
}
}
export async function createContext({ req, res }: CreateFastifyContextOptions) {
async function getUser() {
try {
const apiKey = req.headers['x-api-key']
if (apiKey) {
if (typeof apiKey !== 'string') {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid API key' })
}
const isValid = await validateApiKey(apiKey)
return {
user: null,
isAuthorized: isValid
}
} else {
await req.jwtVerify()
const em = orm.em.fork()
const user = await em.findOne(User, { _id: new ObjectId(req.user.id) })
if (!user) return null
const u = wrap(user).toPOJO()
return {
user: u,
isAuthorized: true
}
}
} catch (err) {
console.log('Error getting user from header or cookie', err)
return null
}
}
const user = await getUser()
return {
req,
res,
user
}
}