Giter Club home page Giter Club logo

nestjs-rest-sample's Introduction

NestJS Sample

Compile and build Build Docker Image Run e2e testing codecov

A NestJS RESTful APIs sample project, including:

  • Restful APIs satisfies Richardson Maturity Model(Level 2)
  • Custom Mongoose integration module instead of @nestjs/mongoose
  • Passport/Jwt authentication with simple text secrets
  • Fully testing codes with Jest, jest-mock-extended, ts-mockito, @golevelup/ts-jest etc.
  • Github actions workflow for continuous testing, code coverage report, docker image building, etc.

Docs

Build

Install the dependencies.

$ npm install

Running the app

# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod

Test

# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov

Reference

nestjs-rest-sample's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar github-actions[bot] avatar hantsy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nestjs-rest-sample's Issues

npm 安装报错

Development Environment:

  • OS: macOS 10.15.7
  • NodeJS version: v14.15.2
  • Package manager tools: npm

Describe the bug
npm install error

npm ERR! code ETARGET
npm ERR! notarget No matching version found for @types/[email protected].
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget 
npm ERR! notarget It was specified as a dependency of 'nestjs-sample'
npm ERR! notarget 

To Reproduce
npm install

Additional context

yarn可以安装成功

RolesGuard jest mock failed

Originally I described it on StackOverflow.
https://stackoverflow.com/questions/62698703/nestjs-rolesguards-failed-in-github-actions-but-passed-in-my-local-system

Currently, I have added 3 versions of testing RolesGuard in the codes.

  • jest (this one dese not work as expected), check here. or see below.
  • ts-mockito
  • jest-mock-extended

After some dependencies upgraded, this test failed with weird errors.

xdescribe('RolesGuard', () => {
  let guard: RolesGuard;
  let reflector: Reflector;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        RolesGuard,
        {
          provide: Reflector,
          useValue: {
            constructor: jest.fn(),
            get: jest.fn(),
          },
        },
      ],
    }).compile();

    guard = module.get<RolesGuard>(RolesGuard);
    reflector = module.get<Reflector>(Reflector);
  });

  afterEach(async () => {
    jest.clearAllMocks();
  });

  it('should be defined', () => {
    expect(guard).toBeDefined();
  });

  it('should skip(return true) if the `HasRoles` decorator is not set', async () => {
    jest.spyOn(reflector, 'get').mockImplementation((a: any, b: any) => []);
    const context = createMock<ExecutionContext>();
    const result = await guard.canActivate(context);

    expect(result).toBeTruthy();
    expect(reflector.get).toBeCalled();
  });

  it('should return true if the `HasRoles` decorator is set', async () => {
    jest
      .spyOn(reflector, 'get')
      .mockImplementation((a: any, b: any) => [RoleType.USER]);
    const context = createMock<ExecutionContext>({
      getHandler: jest.fn(),
      switchToHttp: jest.fn().mockReturnValue({
        getRequest: jest.fn().mockReturnValue({
          user: { roles: [RoleType.USER] },
        } as AuthenticatedRequest),
      }),
    });

    const result = await guard.canActivate(context);
    expect(result).toBeTruthy();
    expect(reflector.get).toBeCalled();
  });

  it('should return false if the `HasRoles` decorator is set but role is not allowed', async () => {
    jest.spyOn(reflector, 'get').mockReturnValue([RoleType.ADMIN]);
    const request = {
      user: { roles: [RoleType.USER] },
    } as AuthenticatedRequest;
    const context = createMock<ExecutionContext>();
    const httpArgsHost = createMock<HttpArgumentsHost>({
      getRequest: () => request,
    });
    context.switchToHttp.mockImplementation(() => httpArgsHost);

    const result = await guard.canActivate(context);
    expect(result).toBeFalsy();
    expect(reflector.get).toBeCalled();
  });
});

Nestjs lifecycle events are not finished as expected with `await app.init` in before hooks

Described on stackoverflow.

https://stackoverflow.com/questions/62699348/nestjs-lifecycle-events-some-time-is-not-executed-as-expected-in-e2e-tests

In the e2e testing codes, app.init did not ensure the execution OnModuleInit.

Sometimes the sample data is filled, sometimes not.

It caused the following tests failed sometime.

it('/posts (GET)', async () => {
      const res = await request(app.getHttpServer()).get('/posts').send();
      expect(res.status).toBe(200);
      expect(res.body.length).toEqual(3);
    });

Add JWT auth

Add JWT based auth to protect RESTful APIs.

  • Local auth to login and get JWT token
  • Set JWT token to protect APIs.

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.