GithubHelp home page GithubHelp logo

alexanderc / redirect Goto Github PK

View Code? Open in Web Editor NEW

This project forked from nestjsplus/redirect

0.0 2.0 0.0 76 KB

Decorator for handling Redirects with NestJS

License: MIT License

JavaScript 2.88% TypeScript 97.12%

redirect's Introduction

Decorator for handling Redirects with NestJS

Installation

npm install @nestjsplus/redirect

Examples

NestJS doesn't currently have a decorator for doing redirects on route handlers. Here's how it looks with this decorator:

@Redirect({statusCode: HttpStatus.TEMPORARY_REDIRECT, url: 'https://nestjs.com'})
@Get('nest')
nest() {
  return;
}

Here's how it looks when the redirect response is determined dynamically:

@Redirect()
@Get('/somelocation')
index() {
  const url = this.getNewLocation();
  return { statusCode: HttpStatus.FOUND, url };
}

Sometimes you want to pass a response rather than redirecting:

@Redirect({ optionalRedirect: true })
@Get('/maybe-redirect')
index() {
  if (someOption) {
    return { hello: 'world' };
  }

  const url = this.getNewLocation();
  return { statusCode: HttpStatus.FOUND, url };
}

Motivation

To do a redirect with Nest out-of-the-box, you either need to utilize the platform-specific response (res) object, or write an interceptor. The former is pretty straightforward, though uses a non-Nest-like imperative style. It also puts you into manual response mode, meaning you can no longer rely on features like @Render(), @HttpCode() or interceptors that modify the response, and makes testing harder (you'll have to mock the response object, etc.).

Writing an interceptor isn't too bad, but wouldn't you rather just plug one in? ❤️ The @Redirect() decorator from this package wraps an interceptor in a declarative decorator that does this for you.

See Also

If you like this little gizmo, you may also be interested in the NestJS Cookie decorators.

Collectively, the @Redirect(), @Cookies(), @SignedCookies(), @SetCookies() and @ClearCookies() decorators in these packages provide a convenient set of features that make it easier to manage redirects and cookies in a standard and declarative way, minimize boilerplate code, and continue to use Nest features like @Headers(), @Render(), and other interceptors that mutate the response.

Importing the Decorator

Import the decorator, just as you would other Nest decorators, in the controllers that use it as shown below:

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { Redirect } from '@nestjsplus/redirect';

@Controller()
export class AppController {
...

Static Redirects

For static redirects, where the statusCode and url (AKA location in the response headers) are known at compile time, simply specify them in the decorator:

@Redirect({statusCode: HttpStatus.TEMPORARY_REDIRECT, url: 'https://nestjs.com'})
@Get('nest')
nest {
  return;
}

Dynamic Redirects

For dynamic redirects, where the statusCode and/or url are computed in the route handler method, return an object from the method with the shape:

interface RedirectOptions {
  /**
   * URL to redirect to.
   */
  url: string;
  /**
   * HTTP Status Code to send.
   */
  statusCode: number;
}

For example:

@Redirect()
@Get('/somelocation')
index() {
  const url = this.getNewLocation();
  return { statusCode: HttpStatus.FOUND, url };
}

Recommendations

Utilize the HttpStatus enum from the @nestjs/common package to ensure you send the correct Http Status Codes, and to get convenient intellisense.

Restrictions

Express Only

This decorator currently only work with Nest applications running on @platform-express. Fastify support is not currently available.

Decorators Can't Access this

Note that decorators have access to the class (Controller), but not the instance. This means that, for example, if you want to pass a variable to a Redirect() decorator, you should pass a variable set in the outer scope of the file (e.g., a const above the controller class definition), as opposed to a property on the controller class.

Change Log

See Changelog for more information.

Contributing

Contributions welcome! See Contributing.

Author

  • John Biundo (Y Prospect on Discord)

License

Licensed under the MIT License - see the LICENSE file for details.

redirect's People

Contributors

alexanderc avatar johnbiundo avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.