├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── README.md ├── docker-compose.yml ├── nest-cli.json ├── package-lock.json ├── package.json ├── schema.gql ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.resolver.ts ├── app.service.ts ├── connection.args.ts ├── entities │ └── zip │ │ └── zip.entity.ts ├── main.ts ├── page-data.ts ├── relay.types.ts └── zip.response.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | sourceType: 'module', 6 | }, 7 | plugins: ['@typescript-eslint/eslint-plugin'], 8 | extends: [ 9 | 'plugin:@typescript-eslint/eslint-recommended', 10 | 'plugin:@typescript-eslint/recommended', 11 | 'prettier', 12 | 'prettier/@typescript-eslint', 13 | ], 14 | root: true, 15 | env: { 16 | node: true, 17 | jest: true, 18 | }, 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/no-explicit-any': 'off', 23 | }, 24 | }; 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | lerna-debug.log* 12 | 13 | # OS 14 | .DS_Store 15 | 16 | # Tests 17 | /coverage 18 | /.nyc_output 19 | 20 | # IDEs and editors 21 | /.idea 22 | .project 23 | .classpath 24 | .c9/ 25 | *.launch 26 | .settings/ 27 | *.sublime-workspace 28 | 29 | # IDE - VSCode 30 | .vscode/* 31 | !.vscode/settings.json 32 | !.vscode/tasks.json 33 | !.vscode/launch.json 34 | !.vscode/extensions.json -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Nest Logo 3 |

4 | 5 | [travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master 6 | [travis-url]: https://travis-ci.org/nestjs/nest 7 | [linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux 8 | [linux-url]: https://travis-ci.org/nestjs/nest 9 | 10 |

A progressive Node.js framework for building efficient and scalable server-side applications, heavily inspired by Angular.

11 |

12 | NPM Version 13 | Package License 14 | NPM Downloads 15 | Travis 16 | Linux 17 | Coverage 18 | Gitter 19 | Backers on Open Collective 20 | Sponsors on Open Collective 21 | 22 | 23 |

24 | 26 | 27 | ## Description 28 | 29 | [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. 30 | 31 | ## Installation 32 | 33 | ```bash 34 | $ npm install 35 | ``` 36 | 37 | ## Running the app 38 | 39 | ```bash 40 | # development 41 | $ npm run start 42 | 43 | # watch mode 44 | $ npm run start:dev 45 | 46 | # production mode 47 | $ npm run start:prod 48 | ``` 49 | 50 | ## Test 51 | 52 | ```bash 53 | # unit tests 54 | $ npm run test 55 | 56 | # e2e tests 57 | $ npm run test:e2e 58 | 59 | # test coverage 60 | $ npm run test:cov 61 | ``` 62 | 63 | ## Support 64 | 65 | 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](https://docs.nestjs.com/support). 66 | 67 | ## Stay in touch 68 | 69 | - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) 70 | - Website - [https://nestjs.com](https://nestjs.com/) 71 | - Twitter - [@nestframework](https://twitter.com/nestframework) 72 | 73 | ## License 74 | 75 | Nest is [MIT licensed](LICENSE). 76 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.7' 2 | services: 3 | mongodb: 4 | image: mongo:latest 5 | container_name: mongodb-nest 6 | environment: 7 | MONGO_INITDB_ROOT_USERNAME: root 8 | MONGO_INITDB_ROOT_PASSWORD: admin 9 | ports: 10 | - 27017:27017 11 | networks: 12 | - nest-net 13 | volumes: 14 | - mongodb_data:/data/db 15 | volumes: 16 | mongodb_data: 17 | driver: local 18 | networks: 19 | nest-net: -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-graphql-cursor-pagination-starter", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "test": "jest", 18 | "test:watch": "jest --watch", 19 | "test:cov": "jest --coverage", 20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 21 | "test:e2e": "jest --config ./test/jest-e2e.json" 22 | }, 23 | "dependencies": { 24 | "@mikro-orm/core": "^4.0.0-rc.8", 25 | "@mikro-orm/mongodb": "^4.0.0-rc.8", 26 | "@mikro-orm/nestjs": "^4.0.0", 27 | "@nestjs/common": "^7.0.0", 28 | "@nestjs/core": "^7.0.0", 29 | "@nestjs/graphql": "^7.6.0", 30 | "@nestjs/platform-express": "^7.0.0", 31 | "apollo-server-express": "^2.17.0", 32 | "class-transformer": "^0.3.1", 33 | "class-validator": "^0.12.2", 34 | "graphql": "^15.3.0", 35 | "graphql-relay": "^0.6.0", 36 | "graphql-tools": "^6.2.1", 37 | "reflect-metadata": "^0.1.13", 38 | "rimraf": "^3.0.2", 39 | "rxjs": "^6.5.4" 40 | }, 41 | "devDependencies": { 42 | "@nestjs/cli": "^7.0.0", 43 | "@nestjs/schematics": "^7.0.0", 44 | "@nestjs/testing": "^7.0.0", 45 | "@types/express": "^4.17.3", 46 | "@types/graphql-relay": "^0.6.0", 47 | "@types/jest": "25.2.3", 48 | "@types/node": "^13.9.1", 49 | "@types/supertest": "^2.0.8", 50 | "@typescript-eslint/eslint-plugin": "3.0.2", 51 | "@typescript-eslint/parser": "3.0.2", 52 | "eslint": "7.1.0", 53 | "eslint-config-prettier": "^6.10.0", 54 | "eslint-plugin-import": "^2.20.1", 55 | "jest": "26.0.1", 56 | "prettier": "^1.19.1", 57 | "supertest": "^4.0.2", 58 | "ts-jest": "26.1.0", 59 | "ts-loader": "^6.2.1", 60 | "ts-node": "^8.6.2", 61 | "tsconfig-paths": "^3.9.0", 62 | "typescript": "^3.7.4" 63 | }, 64 | "jest": { 65 | "moduleFileExtensions": [ 66 | "js", 67 | "json", 68 | "ts" 69 | ], 70 | "rootDir": "src", 71 | "testRegex": ".spec.ts$", 72 | "transform": { 73 | "^.+\\.(t|j)s$": "ts-jest" 74 | }, 75 | "coverageDirectory": "../coverage", 76 | "testEnvironment": "node" 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /schema.gql: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------ 2 | # THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY) 3 | # ------------------------------------------------------ 4 | 5 | type Zip { 6 | id: String 7 | city: String 8 | loc: [Float!] 9 | pop: Float 10 | state: String 11 | } 12 | 13 | type PageData { 14 | count: Float! 15 | limit: Float! 16 | offset: Float! 17 | } 18 | 19 | type ZipResponse { 20 | page: ZipConnection! 21 | pageData: PageData 22 | } 23 | 24 | type ZipConnection { 25 | edges: [ZipEdge!] 26 | pageInfo: ZipPageInfo 27 | } 28 | 29 | type ZipEdge { 30 | cursor: String 31 | node: Zip 32 | } 33 | 34 | type ZipPageInfo { 35 | startCursor: String 36 | endCursor: String 37 | hasPreviousPage: Boolean! 38 | hasNextPage: Boolean! 39 | } 40 | 41 | type Query { 42 | getZips( 43 | """Paginate before opaque cursor""" 44 | before: String 45 | 46 | """Paginate after opaque cursor""" 47 | after: String 48 | 49 | """Paginate first""" 50 | first: Float 51 | 52 | """Paginate last""" 53 | last: Float 54 | ): ZipResponse! 55 | } 56 | -------------------------------------------------------------------------------- /src/app.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | 5 | describe('AppController', () => { 6 | let appController: AppController; 7 | 8 | beforeEach(async () => { 9 | const app: TestingModule = await Test.createTestingModule({ 10 | controllers: [AppController], 11 | providers: [AppService], 12 | }).compile(); 13 | 14 | appController = app.get(AppController); 15 | }); 16 | 17 | describe('root', () => { 18 | it('should return "Hello World!"', () => { 19 | expect(appController.getHello()).toBe('Hello World!'); 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { AppService } from './app.service'; 3 | 4 | @Controller() 5 | export class AppController { 6 | constructor(private readonly appService: AppService) {} 7 | 8 | @Get() 9 | getHello(): string { 10 | return this.appService.getHello(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import { MikroOrmModule } from '@mikro-orm/nestjs' 5 | import Zip from './entities/zip/zip.entity'; 6 | import { GraphQLModule } from '@nestjs/graphql'; 7 | import AppResolver from './app.resolver'; 8 | 9 | @Module({ 10 | imports: [ 11 | MikroOrmModule.forRoot({ 12 | type: 'mongo', 13 | entities: [Zip], 14 | dbName: 'Nest', 15 | debug: true, 16 | clientUrl: 'mongodb://root:admin@localhost:27017' 17 | }), 18 | MikroOrmModule.forFeature({ 19 | entities: [Zip] 20 | }), 21 | GraphQLModule.forRoot({ 22 | autoSchemaFile: './schema.gql', 23 | playground: true 24 | }), 25 | ], 26 | controllers: [AppController], 27 | providers: [AppService, AppResolver], 28 | }) 29 | export class AppModule {} 30 | -------------------------------------------------------------------------------- /src/app.resolver.ts: -------------------------------------------------------------------------------- 1 | import Zip from './entities/zip/zip.entity'; 2 | import { Resolver, Query, Args } from '@nestjs/graphql'; 3 | import { AppService } from './app.service'; 4 | import ZipResponse from './zip.response'; 5 | import ConnectionArgs from './connection.args'; 6 | import { connectionFromArraySlice } from 'graphql-relay'; 7 | 8 | @Resolver(() => Zip) 9 | export default class AppResolver { 10 | private readonly service: AppService 11 | 12 | @Query(() => ZipResponse) 13 | public async getZips(@Args() args: ConnectionArgs): Promise { 14 | const { limit, offset } = args.pagingParams() 15 | const [zips, count] = await this.service.getZips(limit, offset) 16 | const page = connectionFromArraySlice( 17 | zips, args, { arrayLength: count, sliceStart: offset || 0 }, 18 | ) 19 | 20 | return { page, pageData: { count, limit, offset } } 21 | } 22 | 23 | public constructor(service: AppService) { 24 | this.service = service 25 | } 26 | } -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { InjectRepository } from '@mikro-orm/nestjs'; 3 | import Zip from './entities/zip/zip.entity'; 4 | import { EntityRepository } from '@mikro-orm/core'; 5 | 6 | @Injectable() 7 | export class AppService { 8 | getHello(): string { 9 | return 'Hello World!'; 10 | } 11 | 12 | private readonly repo: EntityRepository 13 | 14 | public async getZips(limit: number, offset: number): Promise<[Zip[], number]> { 15 | const zips = await this.repo.findAndCount({}, {limit, offset}) 16 | return zips 17 | } 18 | 19 | public constructor(@InjectRepository(Zip) repo: EntityRepository) { 20 | this.repo = repo 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/connection.args.ts: -------------------------------------------------------------------------------- 1 | 2 | import { ConnectionArguments, ConnectionCursor, fromGlobalId } from 'graphql-relay' 3 | import { Field, ArgsType } from '@nestjs/graphql' 4 | 5 | type PagingMeta = 6 | | { pagingType: 'forward'; after?: string; first: number } 7 | | { pagingType: 'backward'; before?: string; last: number } 8 | | { pagingType: 'none' } 9 | 10 | function checkPagingSanity(args: ConnectionArgs): PagingMeta { 11 | const { 12 | first = 0, last = 0, after, before, 13 | } = args 14 | 15 | const isForwardPaging = !!first || !!after 16 | const isBackwardPaging = !!last || !!before 17 | if (isForwardPaging && isBackwardPaging) { 18 | throw new Error('Relay pagination cannot be forwards AND backwards!') 19 | } 20 | if ((isForwardPaging && before) || (isBackwardPaging && after)) { 21 | throw new Error('Paging must use either first/after or last/before!') 22 | } 23 | if ((isForwardPaging && first < 0) || (isBackwardPaging && last < 0)) { 24 | throw new Error('Paging limit must be positive!') 25 | } 26 | if (last && !before) { 27 | throw new Error("When paging backwards, a 'before' argument is required!") 28 | } 29 | 30 | // eslint-disable-next-line no-nested-ternary 31 | return isForwardPaging 32 | ? { pagingType: 'forward', after, first } 33 | : isBackwardPaging 34 | ? { pagingType: 'backward', before, last } 35 | : { pagingType: 'none' } 36 | } 37 | 38 | const getId = (cursor: ConnectionCursor) => parseInt(fromGlobalId(cursor).id, 10) 39 | const nextId = (cursor: ConnectionCursor) => getId(cursor) + 1 40 | 41 | function getPagingParameters(args: ConnectionArgs) { 42 | const meta = checkPagingSanity(args) 43 | 44 | switch (meta.pagingType) { 45 | case 'forward': { 46 | return { 47 | limit: meta.first, 48 | offset: meta.after ? nextId(meta.after) : 0, 49 | } 50 | } 51 | case 'backward': { 52 | const { last, before } = meta 53 | let limit = last 54 | let offset = getId(before!) - last 55 | 56 | if (offset < 0) { 57 | limit = Math.max(last + offset, 0) 58 | offset = 0 59 | } 60 | 61 | return { offset, limit } 62 | } 63 | default: 64 | return {} 65 | } 66 | } 67 | 68 | @ArgsType() 69 | export default class ConnectionArgs implements ConnectionArguments { 70 | @Field({ nullable: true, description: 'Paginate before opaque cursor' }) 71 | public before?: ConnectionCursor 72 | 73 | @Field({ nullable: true, description: 'Paginate after opaque cursor' }) 74 | public after?: ConnectionCursor 75 | 76 | @Field({ nullable: true, description: 'Paginate first' }) 77 | public first?: number 78 | 79 | @Field({ nullable: true, description: 'Paginate last' }) 80 | public last?: number 81 | 82 | pagingParams() { 83 | return getPagingParameters(this) 84 | } 85 | } -------------------------------------------------------------------------------- /src/entities/zip/zip.entity.ts: -------------------------------------------------------------------------------- 1 | import { ObjectId } from 'mongodb' 2 | import { PrimaryKey, SerializedPrimaryKey, Property, Entity } from '@mikro-orm/core' 3 | import { ObjectType, Field } from '@nestjs/graphql' 4 | 5 | @ObjectType() 6 | @Entity({ tableName: 'Zips' }) 7 | export default class Zip { 8 | @PrimaryKey() 9 | public _id!: ObjectId 10 | 11 | @Field({ nullable: true }) 12 | @SerializedPrimaryKey() 13 | public id!: string 14 | 15 | @Field({ nullable: true }) 16 | @Property() 17 | public city: string 18 | 19 | @Field(() => [Number], { nullable: true }) 20 | @Property() 21 | public loc: number[] 22 | 23 | @Field({ nullable: true }) 24 | @Property() 25 | public pop: number 26 | 27 | @Field({ nullable: true }) 28 | @Property() 29 | public state: string 30 | } -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { ValidationPipe } from '@nestjs/common'; 4 | 5 | async function bootstrap() { 6 | const app = await NestFactory.create(AppModule); 7 | 8 | app.useGlobalPipes(new ValidationPipe({ 9 | transform: true, 10 | transformOptions: { 11 | enableImplicitConversion: true 12 | }, 13 | })) 14 | 15 | await app.listen(3000); 16 | } 17 | bootstrap(); 18 | -------------------------------------------------------------------------------- /src/page-data.ts: -------------------------------------------------------------------------------- 1 | import { Field, ObjectType } from '@nestjs/graphql' 2 | 3 | @ObjectType() 4 | export default class PageData { 5 | @Field() 6 | public count: number 7 | 8 | @Field() 9 | public limit: number 10 | 11 | @Field() 12 | public offset: number 13 | } -------------------------------------------------------------------------------- /src/relay.types.ts: -------------------------------------------------------------------------------- 1 | import * as Relay from 'graphql-relay' 2 | import { ObjectType, Field } from '@nestjs/graphql' 3 | import PageData from './page-data' 4 | import { Type } from '@nestjs/common' 5 | 6 | const typeMap = {} 7 | export default function relayTypes(type: Type): any { 8 | const { name } = type 9 | if (typeMap[`${name}`]) return typeMap[`${name}`] 10 | 11 | @ObjectType(`${name}Edge`, { isAbstract: true }) 12 | class Edge implements Relay.Edge { 13 | public name = `${name}Edge` 14 | 15 | @Field({ nullable: true }) 16 | public cursor!: Relay.ConnectionCursor 17 | 18 | @Field(() => type, { nullable: true }) 19 | public node!: T 20 | 21 | } 22 | 23 | @ObjectType(`${name}PageInfo`, { isAbstract: true }) 24 | class PageInfo implements Relay.PageInfo { 25 | @Field({ nullable: true }) 26 | public startCursor!: Relay.ConnectionCursor 27 | 28 | @Field({ nullable: true }) 29 | public endCursor!: Relay.ConnectionCursor 30 | 31 | @Field(() => Boolean) 32 | public hasPreviousPage!: boolean 33 | 34 | @Field(() => Boolean) 35 | public hasNextPage!: boolean 36 | } 37 | 38 | @ObjectType(`${name}Connection`, { isAbstract: true }) 39 | class Connection implements Relay.Connection { 40 | public name = `${name}Connection` 41 | 42 | @Field(() => [Edge], { nullable: true }) 43 | public edges!: Relay.Edge[] 44 | 45 | @Field(() => PageInfo, { nullable: true }) 46 | public pageInfo!: Relay.PageInfo 47 | } 48 | 49 | @ObjectType(`${name}Page`, { isAbstract: true }) 50 | abstract class Page { 51 | public name = `${name}Page` 52 | 53 | @Field(() => Connection) 54 | public page!: Connection 55 | 56 | @Field(() => PageData, { nullable: true }) 57 | public pageData!: PageData 58 | } 59 | 60 | typeMap[`${name}`] = Page 61 | return typeMap[`${name}`] 62 | } -------------------------------------------------------------------------------- /src/zip.response.ts: -------------------------------------------------------------------------------- 1 | import relayTypes from "./relay.types"; 2 | import Zip from "./entities/zip/zip.entity"; 3 | import { ObjectType } from "@nestjs/graphql"; 4 | 5 | @ObjectType() 6 | export default class ZipResponse extends relayTypes(Zip) { } 7 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true 14 | } 15 | } 16 | --------------------------------------------------------------------------------