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

Make express request injectable #1616

Open
2 of 4 tasks
sourceful-mia opened this issue Apr 24, 2024 · 2 comments
Open
2 of 4 tasks

Make express request injectable #1616

sourceful-mia opened this issue Apr 24, 2024 · 2 comments

Comments

@sourceful-mia
Copy link

Sorting

  • I'm submitting a ...

    • bug report
    • feature request
    • support request
  • I confirm that I

    • used the search to make sure that a similar issue hasn't already been submit

Expected Behavior

I am looking to get the user claims from my JWT so that I can get user id & name. I'd like to make this available everywhere as an injectable service, to avoid every controller route having to worry about passing the request down, and reduce the amount of parameters that need to go through every function.

Possible Solution

I've tried to create a UserService where I inject the request, but it doesn't work:

import { Request } from "tsoa";
import { provide } from "inversify-binding-decorators";
import express from "express";
import { Buffer } from "buffer";

export type User = {
  id: string;
  name: string;
}

@provide(UserService)
export class UserService {
  constructor(@Request() private request: express.Request) {
  }

  async getCurrentUser(): Promise<User> {
    const authHeader = this.request.headers.authorization;
    const jwt = authHeader?.split(" ")[1];

    const claims = Buffer.from(jwt?.split(".")[1] ?? "", "base64").toString();

    return JSON.parse(claims);
  }
}

A couple of other ideas:

  • using a middleware to preload the service and pass the header to it, but there's no way (I can find) to inject that service into my middleware.
  • Make express.Request injectable, but again I'm not sure how I would go about this.

I really like tsoa and how it reduces the amount of (req, res) => {} functions in regular express servers, so I'm keen to avoid having to do this again with this library 😄

Copy link

Hello there sourceful-mia 👋

Thank you for opening your very first issue in this project.

We will try to get back to you as soon as we can.👀

Copy link

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days

@github-actions github-actions bot added the Stale label May 25, 2024
@WoH WoH removed the Stale label May 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants