Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use express middleware with typescript-rest #27

Closed
michaelkruglos opened this issue Aug 17, 2017 · 1 comment
Closed

How to use express middleware with typescript-rest #27

michaelkruglos opened this issue Aug 17, 2017 · 1 comment
Labels

Comments

@michaelkruglos
Copy link

I'd like to have a middleware, like authorization middleware for example.
How can I use middleware with typescript-rest.

Suppose I have something like this:

app = express();
const myMiddleware = (req, res, next) => {
  console.log("I'm in the middle");
  next();
}

@Path("/get")
class MyGetController {
  @GET
  getSomething() {
    return "Some response";
  }
}

app.use('/api', myMiddleware, MyGetController);

How can I do it? How can I augment a class with some middleware in front of it?
How can I use typescript-rest to write middleware, and to compose middleware with controllers?

@thiagobustamante
Copy link
Owner

Typescript-rest receives an express router as parameter to build the routes for all controllers. You can add any middleware to this router as you do using pure express:

app = express();
const myMiddleware = (req, res, next) => {
  console.log("I'm in the middle");
  next();
}

@Path("/get")
class MyGetController {
  @GET
  getSomething() {
    return "Some response";
  }
}
app.use(myMiddleware);
Server.buildServices(app);

Or using a router:

const app = express();
const myMiddleware = (req, res, next) => {
  console.log("I'm in the middle");
  next();
}

@Path("/get")
class MyGetController {
  @GET
  getSomething() {
    return "Some response";
  }
}
const apis = express.Router();
apis.use(myMiddleware);
Server.buildServices(apis);

app.use('/apis', apis);

Remember that, as any other middleware for express, the order where you add your middlewares matters.

For authentication example, check this issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants