Created
March 14, 2019 13:41
-
-
Save sch/d1f73f02e139b7fc131bc9eadf87855b to your computer and use it in GitHub Desktop.
Handling routes with a function instead of middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as express from "express"; | |
const server = express(); | |
server.get("/posts", withAuthenticatedUser(function(req, res, user) { | |
const posts = getPostsForUser(user); | |
res.json(posts); | |
})); | |
server.listen(8080); | |
interface RequestHandlerWithUser { | |
(req: express.Request, res: express.Response, user: User): void; | |
} | |
function withAuthenticatedUser(handler: RequestHandlerWithUser): express.RequestHandler { | |
const routeHandler: express.RequestHandler = (req, res, next) => { | |
findUser(req) | |
.then(user => { | |
if (!user) { | |
res.redirect("/login"); | |
return; | |
} | |
handler(req, res, user); | |
}) | |
.catch(next); | |
}; | |
return routeHandler; | |
} | |
interface User { | |
id: number; | |
name: string; | |
} | |
async function findUser(req: express.Request): Promise<User | null> { | |
if (req.query.online === "extremely") { | |
return { id: 1, name: "Gary" }; | |
} else { | |
return null; | |
} | |
} | |
function getPostsForUser(user: User) { | |
return [{ slug: "jsjsjs", user }]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment