Skip to content

Commit

Permalink
reduce complexity of extend-express-app example
Browse files Browse the repository at this point in the history
  • Loading branch information
dcousens committed Mar 26, 2024
1 parent 1b55b41 commit 07bd259
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 63 deletions.
53 changes: 30 additions & 23 deletions examples/extend-express-app/keystone.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
import { config } from '@keystone-6/core'
import type { Request, Response } from 'express'

import { fixPrismaPath } from '../example-utils'
import { lists } from './schema'
import { getTasks } from './routes/tasks'
import { type TypeInfo, type Context } from '.keystone/types'

function withContext<F extends (req: Request, res: Response, context: Context) => void>(
commonContext: Context,
f: F
) {
return async (req: Request, res: Response) => {
return f(req, res, await commonContext.withRequest(req, res))
}
}
import {
type TypeInfo,
} from '.keystone/types'

export default config<TypeInfo>({
db: {
Expand All @@ -24,18 +15,34 @@ export default config<TypeInfo>({
...fixPrismaPath,
},
server: {
/*
This is the main part of this example. Here we include a function that
takes the express app Keystone created, and does two things:
- Adds a middleware function that will run on requests matching our REST
API routes, to get a keystone context on `req`. This means we don't
need to put our route handlers in a closure and repeat it for each.
- Adds a GET handler for tasks, which will query for tasks in the
Keystone schema and return the results as JSON
*/
extendExpressApp: (app, commonContext) => {
app.get('/rest/tasks', withContext(commonContext, getTasks))
// app.put('/rest/tasks', withContext(commonContext, putTask));
// this example HTTP GET route retrieves any tasks in the database for your context
// using a request query parameter of `complete=true` or `complete=false`
// returning them as JSON
app.get('/rest/tasks', async (req, res) => {
const context = await commonContext.withRequest(req, res)

const isComplete = req.query?.complete === 'true'
const tasks = await context.query.Task.findMany({
where: {
isComplete: {
equals: isComplete
},
},
query: `
id
label
priority
isComplete
assignedTo {
id
name
}
`,
})

res.json(tasks)
})
},
},
lists,
Expand Down
40 changes: 0 additions & 40 deletions examples/extend-express-app/routes/tasks.ts

This file was deleted.

0 comments on commit 07bd259

Please sign in to comment.