Skip to content

Commit

Permalink
docs(@nestjs) update examples, fix interceptors bug
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Sep 5, 2017
1 parent 8de7791 commit 0a6034f
Show file tree
Hide file tree
Showing 55 changed files with 9,003 additions and 30 deletions.
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
## 4.0.0
**@nestjs/core**
- Interceptors feature (docs)
- Guards feature (docs)
- `@Shared()` deprecated (modules are singletons by default)
- `@SingleScope()` decorator (read more in the docs)
- New response handling approach (return plain value / Promise / Observable)
- Async components
- New `INestApplication` methods (for example `use()` wrapper)

**@nestjs/microservices**
- Possibility to return Promise / Observable / plain value
- Guards & Interceptors & Pipes & Exception Filters integration

**@nestjs/websockets**
- Possibility to return Promise / Observable / plain value
- Guards & Interceptors & Pipes & Exception Filters integration

**@nestjs/testing**
- Completely rewritten testing package (docs)

## 3.0.1 (24.06.2017)
**@nestjs/core**
- Hierarchical injector bugfix,
Expand Down
33 changes: 33 additions & 0 deletions examples/01-cats-app/e2e/cats/cats.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as request from 'supertest';
import { Test } from '@nestjs/testing';
import { CatsModule } from '../../src/modules/cats/cats.module';
import { CatsService } from '../../src/modules/cats/cats.service';

describe('Cats', () => {
const server = express();
server.use(bodyParser.json());

const catsService = { findAll: () => ['test'] };

beforeAll(async () => {
const module = await Test.createTestingModule({
modules: [CatsModule],
})
.overrideComponent(CatsService).useValue(catsService)
.compile();

const app = module.createNestApplication(server);
await app.init();
});

it(`/GET cats`, () => {
return request(server)
.get('/cats')
.expect(200)
.expect({
data: catsService.findAll(),
});
});
});
14 changes: 14 additions & 0 deletions examples/01-cats-app/e2e/jest-e2e.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json"
],
"transform": {
"^.+\\.tsx?$": "<rootDir>/../node_modules/ts-jest/preprocessor.js"
},
"testRegex": "/e2e/.*\\.(e2e-test|e2e-spec).(ts|tsx|js)$",
"collectCoverageFrom" : ["src/**/*.{js,jsx,tsx,ts}", "!**/node_modules/**", "!**/vendor/**"],
"coverageReporters": ["json", "lcov"]
}
14 changes: 14 additions & 0 deletions examples/01-cats-app/jest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json"
],
"transform": {
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "/src/.*\\.(test|spec).(ts|tsx|js)$",
"collectCoverageFrom" : ["src/**/*.{js,jsx,tsx,ts}", "!**/node_modules/**", "!**/vendor/**"],
"coverageReporters": ["json", "lcov"]
}
11 changes: 10 additions & 1 deletion examples/01-cats-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
"scripts": {
"start": "node index.js",
"prestart:prod": "tsc",
"start:prod": "node dist/server.js"
"start:prod": "node dist/server.js",
"test": "jest --config=jest.json",
"test:watch": "jest --watch --config=jest.json",
"test:coverage": "jest --config=jest.json --coverage --coverageDirectory=coverage",
"e2e": "jest --config=e2e/jest-e2e.json",
"e2e:watch": "jest --watch --config=e2e/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^3.0.3",
Expand All @@ -23,7 +28,11 @@
"typescript": "^2.4.2"
},
"devDependencies": {
"@types/jest": "^20.0.8",
"@types/node": "^7.0.41",
"jest": "^20.0.4",
"supertest": "^3.0.0",
"ts-jest": "^20.0.14",
"ts-node": "^3.3.0"
}
}
27 changes: 27 additions & 0 deletions examples/01-cats-app/src/modules/cats/cats.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Test } from '@nestjs/testing';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

describe('CatsController', () => {
let catsController: CatsController;
let catsService: CatsService;

beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [CatsController],
components: [CatsService],
}).compile();

catsService = module.get<CatsService>(CatsService);
catsController = module.get<CatsController>(CatsController);
});

describe('findAll', () => {
it('should return an array of cats', async () => {
const result = ['test'];
jest.spyOn(catsService, 'findAll').mockImplementation(() => result);

expect(await catsController.findAll()).toBe(result);
});
});
});
11 changes: 8 additions & 3 deletions examples/01-cats-app/src/modules/cats/cats.controller.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import { Controller, Get, Post, Body, UseGuards } from '@nestjs/common';
import { Controller, Get, Post, Body, UseGuards, ReflectMetadata, UseInterceptors } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';
import { BreedGuard } from '../common/guards/breed.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import { LoggingInterceptor } from '../common/interceptors/logging.interceptor';
import { TransformInterceptor } from '../common/interceptors/transform.interceptor';

@Controller('cats')
@UseGuards(RolesGuard)
@UseInterceptors(LoggingInterceptor, TransformInterceptor)
export class CatsController {
constructor(private readonly catsService: CatsService) {}

@Post()
@UseGuards(BreedGuard)
@Roles('admin')
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { ReflectMetadata } from '@nestjs/common';

export const Roles = (...roles: string[]) => ReflectMetadata('roles', roles);
11 changes: 0 additions & 11 deletions examples/01-cats-app/src/modules/common/guards/breed.guard.ts

This file was deleted.

20 changes: 20 additions & 0 deletions examples/01-cats-app/src/modules/common/guards/roles.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Guard, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs/Observable';
import { Reflector } from '@nestjs/core';

@Guard()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}

canActivate(req, context: ExecutionContext): boolean {
const { parent, handler } = context;
const roles = this.reflector.get<string[]>('roles', handler);
if (!roles) {
return true;
}

const user = req.user;
const hasRole = () => !!user.roles.find((role) => !!roles.find((item) => item === role));
return user && user.roles && hasRole();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Interceptor, NestInterceptor, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Interceptor()
export class CacheInterceptor implements NestInterceptor {
intercept(dataOrRequest, context: ExecutionContext, stream$: Observable<any>): Observable<any> {
const isCached = true;
if (isCached) {
return Observable.of([]);
}
return stream$;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Interceptor, NestInterceptor, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Interceptor()
export class LoggingInterceptor implements NestInterceptor {
intercept(dataOrRequest, context: ExecutionContext, stream$: Observable<any>): Observable<any> {
console.log('Before...');
const now = Date.now();

return stream$.do(
() => console.log(`After... ${Date.now() - now}ms`),
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Interceptor, NestInterceptor, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Interceptor()
export class TransformInterceptor implements NestInterceptor {
intercept(dataOrRequest, context: ExecutionContext, stream$: Observable<any>): Observable<any> {
return stream$.map((data) => ({ data }));
}
}
21 changes: 21 additions & 0 deletions examples/02-gateways/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# dependencies
/node_modules

# IDE
/.idea
/.awcache
/.vscode

# misc
npm-debug.log

# example
/quick-start

# tests
/test
/coverage
/.nyc_output

# dist
/dist
22 changes: 22 additions & 0 deletions examples/02-gateways/client/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<html>
<head>
<script src="socket.io.js"></script>
<script>
const socket = io('http://localhost:81');
socket.on('connect', function() {
console.log('Connected');
socket.emit('events', { test: 'test' });
});
socket.on('events', function(data) {
console.log('event', data);
});
socket.on('exception', function(data) {
console.log('event', data);
});
socket.on('disconnect', function() {
console.log('Disconnected');
});
</script>
</head>
<body></body>
</html>
Loading

0 comments on commit 0a6034f

Please sign in to comment.