Skip to main content

Context

Each middleware and transform function is passed a custom context object. This object is used for passing data from one middleware to the next, without altering the data object (since altering the data object changes the query we make to your database).

The context object is also injected with any custom data that you set from the client. For more information about context, see this guide.

You can do whatever you want with the ctx object.

Context is useful for managing permissions, keeping state, and many other things.

Examples

A simple example of using context to track if a user is an admin or not in the middleware cycle

const userIsAdmin = ({ data, ctx, next }) => {
if(data.UserId === '123') {
ctx.isAdmin = true;
}
next(data, ctx);
}
const addDataIfAdmin = ({ data, ctx, next }) => {
if(ctx.isAdmin) {
// do some other logic here
}
next(data, ctx)
}
const resolvers = SQLResolverGenerator({
info: {
Documents: {
table: 'Documents',
writeMiddleware: [
userIsAdmin,
addDataIfAdmin
],
columns: {
...columnMap
},
},
}
})

A sample showing how to use context to transform values

// on the client
client.setContext({
username: 'PDFTron'
})
// Server side
const resolvers = SQLResolverGenerator({
info: {
Users: {
table: 'customers',
columns: {
userName: {
name: 'UserName',
transform: (_, context) => context.username // Get value from context. Returns "PDFTron"
},
},
},
}
})