New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@waitaction/nestjs-ng-universal

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@waitaction/nestjs-ng-universal

Nest - modern, fast, powerful node.js web framework (@ng-universal)

latest
npmnpm
Version
11.0.0
Version published
Maintainers
1
Created
Source

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

<p align="center">

NPM Version Package License NPM Downloads Travis Linux Coverage Discord Backers on Open Collective Sponsors on Open Collective

Description

Angular Universal module for Nest.

Installation

Using the Angular CLI:

$ ng add @waitaction/nestjs-ng-universal

Or manually:

$ npm i @waitaction/nestjs-ng-universal

Example

See full example here.

Usage

If you have installed the module manually, you need to import AngularUniversalModule in your Nest application.

import { Module } from '@nestjs/common';
import { join } from 'path';
import { AngularUniversalModule } from '@waitaction/nestjs-ng-universal';

@Module({
  imports: [
    AngularUniversalModule.forRoot({
      bootstrap: AppServerModule,
      viewsPath: join(process.cwd(), 'dist/{APP_NAME}/browser')
    }),
  ],
})
export class ApplicationModule {}

useEjsEngine 设置为 true 则输出不渲染的html

API Spec

The forRoot() method takes an options object with a few useful properties.

PropertyTypeDescription
viewsPathstringThe directory where the module should look for client bundle (Angular app)
bootstrapFunctionAngular server module reference ( AppServerModule ).
templatePathstring?Path to index file (default: {viewsPaths}/index.html )
rootStaticPathstring?Static files root directory (default: *.* )
renderPathstring?Path to render Angular app (default: * )
extraProvidersStaticProvider[]?The platform level providers for the current render request
cacheboolean? | object?Cache options, description below (default: true )
useEjsEngineboolean?HTML that is not rendered on the server (default: false )

Cache

PropertyTypeDescription
expiresInnumber?Cache expiration in milliseconds (default: 60000 )
storageCacheStorage?Interface for implementing custom cache storage (default: in memory)
keyGeneratorCacheKeyGenerator?Interface for implementing custom cache key generation logic (default: by url)
AngularUniversalModule.forRoot({
  bootstrap: AppServerModule,
  viewsPath: join(process.cwd(), 'dist/{APP_NAME}/browser'),
  cache: {
    storage: new InMemoryCacheStorage(),
    expiresIn: DEFAULT_CACHE_EXPIRATION_TIME,
    keyGenerator: new CustomCacheKeyGenerator(),
  }
})

Example for CacheKeyGenerator:

export class CustomCacheKeyGenerator implements CacheKeyGenerator {
  generateCacheKey(request: Request): string {
    const md = new MobileDetect(request.headers['user-agent']);
    const isMobile = md.mobile() ? 'mobile' : 'desktop';
    return (request.hostname + request.originalUrl + isMobile).toLowerCase();
  }
}

Request and Response Providers

This tool uses @nguniversal/express-engine and will properly provide access to the Express Request and Response objects in you Angular components.

This is useful for things like setting the response code to 404 when your Angular router can't find a page (i.e. path: '**' in routing):

import { Response } from 'express';
import { Component, Inject, Optional, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { RESPONSE } from '@nguniversal/express-engine/tokens';

@Component({
  selector: 'my-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.scss'],
})
export class NotFoundComponent {
  constructor(
    @Inject(PLATFORM_ID)
    private readonly platformId: any,
    @Optional()
    @Inject(RESPONSE)
    res: Response,
  ) {
    // `res` is the express response, only available on the server
    if (isPlatformServer(this.platformId)) {
      res.status(404);
    }
  }
}

The server and client share the CookieService .

import { makeStateKey, TransferState } from '@angular/platform-browser';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse } from '@angular/common/http';
import { tap } from 'rxjs/operators';
import { CookieService } from '@gorniv/ngx-universal';
import { TokenService } from '../token.service';

@Injectable()
export class ServerStateInterceptor implements HttpInterceptor {

    constructor(
        private transferState: TransferState,
        private tokenService: TokenService,
        private cookieService: CookieService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        let self = this;
        return next.handle(req).pipe(
            tap(event => {
                if (event instanceof HttpResponse) {
                    this.transferState.set(makeStateKey(self.tokenService.computedUrlKey(req.url)), event.body);
                    this.cookieService.put(self.tokenService.computedUrlKey(req.url), "server");
                }
            })
        );
    }
}

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

Stay in touch

License

Nest is MIT licensed.

FAQs

Package last updated on 01 Apr 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts