Reading Recommendation: Overview > Tour.
Telefunctions can use getContext()
to access information about the logged-in user:
// TodoList.telefunc.js
// Environment: Node.js
import { getContext } from 'telefunc'
export { getTodoItems }
async function getTodoItems() {
const { user } = getContext()
// We use `user.id` to find all to-do items of the logged-in user
const authorId = user.id
const todoItems = await Todo.findMany({ select: 'text', authorId })
return todoItems
}
We determine the context object by using provideTelefuncContext()
.
// server.js
// Environment: Node.js
import { provideTelefuncContext } from 'telefunc'
// Server middleware (Express.js/Fastify/Koa/Hapi/...)
app.all('/_telefunc', async (req, res) => {
// Authentication middlewares (e.g. Passport.js or Grant) usually provide information
// about the logged-in user on the `req` object.
const user = req.user
// Or when using a third-party authentication provider (e.g. Auth0):
const user = await authProviderApi.getUser(req.headers)
// We make `user` available to our telefunctions
provideTelefuncContext({ user })
// The usual Telefunc integration
const httpResponse = await telefunc({ url: req.url, method: req.method, body: req.body })
const { body, statusCode, contentType } = httpResponse
res.status(statusCode).type(contentType).send(body)
})
getContext()
wrappersFor convenience, we can implement getContext()
wrappers.
// auth/getUser.ts
// Environment: Node.js
// Note that `auth/getUser.ts` is not a `.telefunc.js` file and `getUser()` not a telefunction
export { getUser }
import { Abort, getContext } from 'telefunc'
function getUser() {
const { user } = getContext()
if (!user) {
throw Abort()
}
return user
}
Such wrappers allow us to achieve advanced permissions and hardened safety, see Guides > Permissions > getContext()
wrappers.