Skip to content

Instantly share code, notes, and snippets.

@sch
Created March 14, 2019 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sch/d1f73f02e139b7fc131bc9eadf87855b to your computer and use it in GitHub Desktop.
Save sch/d1f73f02e139b7fc131bc9eadf87855b to your computer and use it in GitHub Desktop.
Handling routes with a function instead of middleware
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