├── .DS_Store ├── README.md ├── nestjs-noted ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── .vscode │ └── settings.json ├── LICENSE ├── README.md ├── nest-cli.json ├── package-lock.json ├── package.json ├── src │ ├── app.module.ts │ ├── main.ts │ ├── todo │ │ ├── controllers │ │ │ ├── index.ts │ │ │ └── todo.controller.ts │ │ ├── dto │ │ │ ├── add-todo.dto.ts │ │ │ ├── edit-todo.dto.ts │ │ │ ├── index.ts │ │ │ └── todo.dto.ts │ │ ├── entities │ │ │ ├── index.ts │ │ │ └── todo.entity.ts │ │ ├── services │ │ │ ├── index.ts │ │ │ ├── todo-mapper │ │ │ │ ├── todo-mapper.service.spec.ts │ │ │ │ └── todo-mapper.service.ts │ │ │ └── todo │ │ │ │ ├── todo.service.spec.ts │ │ │ │ └── todo.service.ts │ │ └── todo.module.ts │ └── utils │ │ └── test │ │ └── repository.mock.ts ├── test │ ├── app.e2e-spec.ts │ └── jest-e2e.json ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock └── noted-client ├── .eslintcache ├── .gitignore ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.css ├── App.tsx ├── app │ └── store.ts ├── features │ └── todo │ │ ├── AddTodo.tsx │ │ ├── TodoItem.tsx │ │ └── index.ts ├── hooks │ └── useApi.tsx ├── index.css ├── index.tsx ├── logo.svg ├── react-app-env.d.ts ├── serviceWorker.ts ├── services │ ├── api │ │ ├── hooks │ │ │ └── useTodos.tsx │ │ └── todo.ts │ └── openapi │ │ ├── core │ │ ├── ApiError.ts │ │ ├── ApiRequestOptions.ts │ │ ├── ApiResult.ts │ │ ├── OpenAPI.ts │ │ └── request.ts │ │ ├── index.ts │ │ ├── models │ │ ├── AddTodoDto.ts │ │ ├── EditTodoDto.ts │ │ └── TodoDto.ts │ │ └── services │ │ └── TodosService.ts └── setupTests.ts ├── tsconfig.json └── yarn.lock /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LogRocket-Tutorials/OpenAPI/5a5f3c362d53ed971f904a94123f2eaf8ec35a0c/.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenAPI 2 | -------------------------------------------------------------------------------- /nestjs-noted/.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 | -------------------------------------------------------------------------------- /nestjs-noted/.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 35 | db.sqlite 36 | -------------------------------------------------------------------------------- /nestjs-noted/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /nestjs-noted/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "debug.node.autoAttach": "on", 3 | "cSpell.words": [ 4 | "todos" 5 | ] 6 | } -------------------------------------------------------------------------------- /nestjs-noted/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Iacopo Ciao 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /nestjs-noted/README.md: -------------------------------------------------------------------------------- 1 | # nestjs-todo-app 2 | 3 | ## Description 4 | 5 | Simple ToDo application using [NestJS](https://github.com/nestjs/nest). 6 | 7 | ## Installation 8 | 9 | ```bash 10 | $ npm install 11 | ``` 12 | 13 | ## Running the app 14 | 15 | ```bash 16 | # development 17 | $ npm run start 18 | 19 | # watch mode 20 | $ npm run start:dev 21 | 22 | # production mode 23 | $ npm run start:prod 24 | ``` 25 | 26 | ## Test 27 | 28 | ```bash 29 | # unit tests 30 | $ npm run test 31 | 32 | # e2e tests 33 | $ npm run test:e2e 34 | 35 | # test coverage 36 | $ npm run test:cov 37 | ``` 38 | 39 | ## License 40 | 41 | nestjs-todo-app is [MIT licensed](LICENSE). 42 | -------------------------------------------------------------------------------- /nestjs-noted/nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /nestjs-noted/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "todo-backend", 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 | "@nestjs/common": "^7.0.0", 25 | "@nestjs/core": "^7.0.0", 26 | "@nestjs/platform-express": "^7.0.0", 27 | "@nestjs/typeorm": "^7.1.3", 28 | "class-transformer": "^0.3.1", 29 | "class-validator": "^0.12.2", 30 | "reflect-metadata": "^0.1.13", 31 | "rimraf": "^3.0.2", 32 | "rxjs": "^6.5.4", 33 | "sqlite": "^4.0.14", 34 | "sqlite3": "^5.0.0", 35 | "typeorm": "^0.2.25" 36 | }, 37 | "devDependencies": { 38 | "@nestjs/cli": "^7.0.0", 39 | "@nestjs/schematics": "^7.0.0", 40 | "@nestjs/swagger": "^4.7.12", 41 | "@nestjs/testing": "^7.0.0", 42 | "@types/express": "^4.17.3", 43 | "@types/jest": "25.2.3", 44 | "@types/node": "^13.9.1", 45 | "@types/supertest": "^2.0.8", 46 | "@types/reactstrap": "^8.4.1", 47 | "@typescript-eslint/eslint-plugin": "^4.0.0", 48 | "@typescript-eslint/parser": "^4.0.0", 49 | "babel-eslint": "^10.0.0", 50 | "eslint": "7.1.0", 51 | "eslint-config-prettier": "^6.10.0", 52 | "eslint-plugin-import": "^2.20.1", 53 | "jest": "26.0.1", 54 | "prettier": "^1.19.1", 55 | "supertest": "^4.0.2", 56 | "swagger-ui-express": "^4.1.6", 57 | "ts-jest": "26.1.0", 58 | "ts-loader": "^6.2.1", 59 | "ts-node": "^8.6.2", 60 | "tsconfig-paths": "^3.9.0", 61 | "typescript": "^3.7.4" 62 | }, 63 | "jest": { 64 | "moduleFileExtensions": [ 65 | "js", 66 | "json", 67 | "ts" 68 | ], 69 | "rootDir": "src", 70 | "testRegex": ".spec.ts$", 71 | "transform": { 72 | "^.+\\.(t|j)s$": "ts-jest" 73 | }, 74 | "coverageDirectory": "../coverage", 75 | "testEnvironment": "node" 76 | } 77 | } -------------------------------------------------------------------------------- /nestjs-noted/src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import * as path from 'path'; 4 | import { TodoModule } from './todo/todo.module'; 5 | 6 | @Module({ 7 | imports: [ 8 | TypeOrmModule.forRoot({ 9 | type: 'sqlite', 10 | autoLoadEntities: true, 11 | synchronize: true, 12 | database: path.resolve(__dirname, '..', 'db.sqlite') 13 | }), 14 | TodoModule 15 | ] 16 | }) 17 | export class AppModule {} 18 | -------------------------------------------------------------------------------- /nestjs-noted/src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { 3 | SwaggerModule, 4 | DocumentBuilder, 5 | SwaggerDocumentOptions, 6 | } from '@nestjs/swagger'; 7 | import { AppModule } from './app.module'; 8 | import { ValidationPipe } from '@nestjs/common'; 9 | 10 | async function bootstrap() { 11 | const app = await NestFactory.create(AppModule); 12 | 13 | app.useGlobalPipes(new ValidationPipe({ transform: true })); 14 | app.enableCors(); 15 | 16 | const config = new DocumentBuilder() 17 | .setTitle('Noted') 18 | .setDescription('API description for Noted') 19 | .setVersion('1.0') 20 | .addTag('noted') 21 | .build(); 22 | 23 | const options: SwaggerDocumentOptions = { 24 | operationIdFactory: (_controllerKey: string, methodKey: string) => 25 | methodKey, 26 | }; 27 | const document = SwaggerModule.createDocument(app, config, options); 28 | 29 | SwaggerModule.setup('api', app, document); 30 | 31 | await app.listen(3000); 32 | } 33 | bootstrap(); 34 | -------------------------------------------------------------------------------- /nestjs-noted/src/todo/controllers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './todo.controller'; -------------------------------------------------------------------------------- /nestjs-noted/src/todo/controllers/todo.controller.ts: -------------------------------------------------------------------------------- 1 | import { TodoService } from './../services/todo/todo.service'; 2 | import { TodoDto, AddTodoDto, EditTodoDto } from './../dto'; 3 | 4 | import { 5 | Controller, 6 | Get, 7 | Param, 8 | Post, 9 | Put, 10 | Body, 11 | Delete, 12 | } from '@nestjs/common'; 13 | import { ApiResponse, ApiTags } from '@nestjs/swagger'; 14 | 15 | @ApiTags('todos') 16 | @Controller('todos') 17 | export class TodoController { 18 | public constructor(private readonly todoService: TodoService) {} 19 | 20 | @Get() 21 | @ApiResponse({ 22 | status: 200, 23 | description: 'Found todo', 24 | type: [TodoDto], 25 | }) 26 | public findAll(): Promise { 27 | return this.todoService.findAll(); 28 | } 29 | 30 | @Get(':id') 31 | public findOne(@Param('id') id: number): Promise { 32 | return this.todoService.findOne(id); 33 | } 34 | 35 | @Put(':id') 36 | public edit( 37 | @Param('id') id: number, 38 | @Body() todo: EditTodoDto, 39 | ): Promise { 40 | return this.todoService.edit(id, todo); 41 | } 42 | 43 | @Post() 44 | public add(@Body() todo: AddTodoDto): Promise { 45 | return this.todoService.add(todo); 46 | } 47 | 48 | @Delete(':id') 49 | public remove(@Param('id') id: number): Promise { 50 | return this.todoService.remove(id); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /nestjs-noted/src/todo/dto/add-todo.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsString, IsNotEmpty } from 'class-validator'; 3 | 4 | export class AddTodoDto { 5 | @IsString() 6 | @IsNotEmpty() 7 | @ApiProperty() 8 | public readonly title: string; 9 | 10 | @IsString() 11 | @ApiProperty() 12 | public readonly text: string; 13 | 14 | public constructor(opts?: Partial) { 15 | Object.assign(this, opts); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /nestjs-noted/src/todo/dto/edit-todo.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsBoolean, IsNotEmpty, IsString } from 'class-validator'; 3 | 4 | export class EditTodoDto { 5 | @ApiProperty() 6 | @IsString() 7 | @IsNotEmpty() 8 | public readonly title: string; 9 | 10 | @ApiProperty() 11 | @IsString() 12 | @IsNotEmpty() 13 | public readonly text: string; 14 | 15 | @ApiProperty() 16 | @IsBoolean() 17 | public readonly completed: boolean; 18 | 19 | public constructor(opts?: Partial) { 20 | Object.assign(this, opts); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /nestjs-noted/src/todo/dto/index.ts: -------------------------------------------------------------------------------- 1 | export * from './add-todo.dto'; 2 | export * from './todo.dto'; 3 | export * from './edit-todo.dto'; -------------------------------------------------------------------------------- /nestjs-noted/src/todo/dto/todo.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class TodoDto { 4 | @ApiProperty() 5 | @ApiProperty({ example: 1, description: 'Auto Generated Id' }) 6 | public readonly id: number; 7 | 8 | @ApiProperty() 9 | @ApiProperty({ example: 'Clean the yard', description: 'Title for todo' }) 10 | public readonly title: string; 11 | 12 | @ApiProperty() 13 | @ApiProperty({ example: 'Clean yard at 5pm', description: 'Body of todo' }) 14 | public readonly text: string; 15 | 16 | @ApiProperty() 17 | public readonly completed: boolean; 18 | 19 | public constructor(opts?: Partial) { 20 | Object.assign(this, opts); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /nestjs-noted/src/todo/entities/index.ts: -------------------------------------------------------------------------------- 1 | export * from './todo.entity'; -------------------------------------------------------------------------------- /nestjs-noted/src/todo/entities/todo.entity.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; 3 | 4 | @Entity() 5 | export class Todo { 6 | @ApiProperty({ example: 1, description: 'Auto Generated Id' }) 7 | @PrimaryGeneratedColumn() 8 | public id: number; 9 | 10 | @Column() 11 | @ApiProperty({ example: 'Clean the yard', description: 'Title for todo' }) 12 | public title: string; 13 | 14 | @Column() 15 | @ApiProperty({ example: 'Clean yard at 5pm', description: 'Body of todo' }) 16 | public text: string; 17 | 18 | @Column() 19 | public completed: boolean; 20 | 21 | public constructor(title: string, text: string) { 22 | this.title = title; 23 | this.text = text; 24 | this.completed = false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /nestjs-noted/src/todo/services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './todo/todo.service'; 2 | export * from './todo-mapper/todo-mapper.service'; -------------------------------------------------------------------------------- /nestjs-noted/src/todo/services/todo-mapper/todo-mapper.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TodoMapperService } from './todo-mapper.service'; 3 | import { Todo } from './../../entities'; 4 | import { TodoDto } from './../../dto'; 5 | 6 | describe('TodoMapperService', () => { 7 | let service: TodoMapperService; 8 | 9 | beforeEach(async () => { 10 | const module: TestingModule = await Test.createTestingModule({ 11 | providers: [TodoMapperService], 12 | }).compile(); 13 | 14 | service = module.get(TodoMapperService); 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(service).toBeDefined(); 19 | }); 20 | 21 | it('should convert model to dto', () => { 22 | const todo = new Todo('test'); 23 | 24 | expect(service.modelToDto(todo)).toEqual(new TodoDto({ title: 'test', completed: false })) 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /nestjs-noted/src/todo/services/todo-mapper/todo-mapper.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { Todo } from '../../entities'; 3 | import { TodoDto } from '../../dto'; 4 | 5 | @Injectable() 6 | export class TodoMapperService { 7 | public modelToDto({ id, title, text, completed }: Todo): TodoDto { 8 | return new TodoDto({ id, title, text, completed }); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /nestjs-noted/src/todo/services/todo/todo.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TodoService } from './todo.service'; 3 | import { getRepositoryToken } from '@nestjs/typeorm'; 4 | import { Todo } from './../../entities'; 5 | import { repositoryMockFactory, MockType } from './../../../utils/test/repository.mock'; 6 | import { TodoMapperService } from './../todo-mapper/todo-mapper.service'; 7 | import { Repository } from 'typeorm'; 8 | 9 | describe('TodoService', () => { 10 | let service: TodoService; 11 | let repository: MockType>; 12 | 13 | beforeEach(async () => { 14 | const module: TestingModule = await Test.createTestingModule({ 15 | providers: [ 16 | TodoService, 17 | TodoMapperService, 18 | { provide: getRepositoryToken(Todo), useFactory: repositoryMockFactory } 19 | ], 20 | }).compile(); 21 | repository = module.get>(getRepositoryToken(Todo)) as unknown as MockType>; 22 | service = module.get(TodoService); 23 | }); 24 | 25 | it('should be defined', () => { 26 | expect(service).toBeDefined(); 27 | }); 28 | 29 | it('should throws exception when todo not exists', async () => { 30 | repository.findOne.mockReturnValue(Promise.resolve(null)); 31 | await expect(service.findOne(1)).rejects.toThrow('Not Found'); 32 | }); 33 | 34 | }); -------------------------------------------------------------------------------- /nestjs-noted/src/todo/services/todo/todo.service.ts: -------------------------------------------------------------------------------- 1 | import { isNullOrUndefined } from 'util'; 2 | import { Injectable, NotFoundException } from '@nestjs/common'; 3 | import { Repository } from 'typeorm'; 4 | import { InjectRepository } from '@nestjs/typeorm'; 5 | import { Todo } from '../../entities'; 6 | import { TodoDto, AddTodoDto, EditTodoDto } from '../../dto'; 7 | import { TodoMapperService } from '../todo-mapper/todo-mapper.service'; 8 | 9 | @Injectable() 10 | export class TodoService { 11 | public constructor( 12 | @InjectRepository(Todo) private readonly todoRepository: Repository, 13 | private readonly todoMapper: TodoMapperService, 14 | ) {} 15 | 16 | public async findAll(): Promise { 17 | const todos = await this.todoRepository.find(); 18 | return todos.map(this.todoMapper.modelToDto); 19 | } 20 | 21 | public async findOne(id: number): Promise { 22 | const todo = await this.todoRepository.findOne(id); 23 | if (isNullOrUndefined(todo)) throw new NotFoundException(); 24 | return this.todoMapper.modelToDto(todo); 25 | } 26 | 27 | public async add({ title, text }: AddTodoDto): Promise { 28 | let todo = new Todo(title, text); 29 | todo = await this.todoRepository.save(todo); 30 | return this.todoMapper.modelToDto(todo); 31 | } 32 | 33 | public async edit( 34 | id: number, 35 | { title, completed }: EditTodoDto, 36 | ): Promise { 37 | let todo = await this.todoRepository.findOne(id); 38 | 39 | if (isNullOrUndefined(todo)) throw new NotFoundException(); 40 | 41 | todo.completed = completed; 42 | todo.title = title; 43 | 44 | todo = await this.todoRepository.save(todo); 45 | 46 | return this.todoMapper.modelToDto(todo); 47 | } 48 | 49 | public async remove(id: number): Promise { 50 | let todo = await this.todoRepository.findOne(id); 51 | 52 | if (isNullOrUndefined(todo)) throw new NotFoundException(); 53 | 54 | todo = await this.todoRepository.remove(todo); 55 | 56 | return todo; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /nestjs-noted/src/todo/todo.module.ts: -------------------------------------------------------------------------------- 1 | import { TodoController } from './controllers'; 2 | import { Module } from '@nestjs/common'; 3 | import { TypeOrmModule } from '@nestjs/typeorm'; 4 | import { Todo } from './entities'; 5 | import { TodoService, TodoMapperService } from './services'; 6 | 7 | @Module({ 8 | imports: [ 9 | TypeOrmModule.forFeature([Todo]) 10 | ], 11 | providers: [ 12 | TodoService, 13 | TodoMapperService 14 | ], 15 | controllers: [ 16 | TodoController 17 | ] 18 | }) 19 | export class TodoModule {} 20 | -------------------------------------------------------------------------------- /nestjs-noted/src/utils/test/repository.mock.ts: -------------------------------------------------------------------------------- 1 | import { Repository } from "typeorm"; 2 | 3 | export type MockType = { 4 | [P in keyof T]: jest.Mock; 5 | }; 6 | 7 | export const repositoryMockFactory: () => MockType> = jest.fn(() =>({ 8 | manager: jest.fn(), 9 | metadata: jest.fn(), 10 | queryRunner: jest.fn(), 11 | createQueryBuilder: jest.fn(), 12 | target: jest.fn(), 13 | hasId: jest.fn(), 14 | getId: jest.fn(), 15 | create: jest.fn(), 16 | merge: jest.fn(), 17 | preload: jest.fn(), 18 | save: jest.fn(), 19 | remove: jest.fn(), 20 | softRemove: jest.fn(), 21 | recover: jest.fn(), 22 | insert: jest.fn(), 23 | update: jest.fn(), 24 | delete: jest.fn(), 25 | softDelete: jest.fn(), 26 | restore: jest.fn(), 27 | count: jest.fn(), 28 | find: jest.fn(), 29 | findAndCount: jest.fn(), 30 | findByIds: jest.fn(), 31 | findOne: jest.fn(), 32 | findOneOrFail: jest.fn(), 33 | query: jest.fn(), 34 | clear: jest.fn(), 35 | increment: jest.fn(), 36 | decrement: jest.fn() 37 | })); 38 | 39 | -------------------------------------------------------------------------------- /nestjs-noted/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 | -------------------------------------------------------------------------------- /nestjs-noted/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 | -------------------------------------------------------------------------------- /nestjs-noted/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /nestjs-noted/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 | -------------------------------------------------------------------------------- /noted-client/.eslintcache: -------------------------------------------------------------------------------- 1 | [{"/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/index.tsx":"1","/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/serviceWorker.ts":"2","/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/app/store.ts":"3","/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/App.tsx":"4","/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/app/rootReducer.ts":"5","/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/features/auth/index.ts":"6","/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/hooks/useLocalStorage.tsx":"7"},{"size":646,"mtime":1612211790875,"results":"8","hashOfConfig":"9"},{"size":5424,"mtime":1608673489009,"results":"10","hashOfConfig":"9"},{"size":494,"mtime":1612211769549,"results":"11","hashOfConfig":"9"},{"size":154,"mtime":1612211937334,"results":"12","hashOfConfig":"9"},{"size":253,"mtime":1612211915761,"results":"13","hashOfConfig":"9"},{"size":2400,"mtime":1612211882999,"results":"14","hashOfConfig":"9"},{"size":540,"mtime":1608674170322,"results":"15","hashOfConfig":"9"},{"filePath":"16","messages":"17","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"zt47bc",{"filePath":"18","messages":"19","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"20","messages":"21","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"22","messages":"23","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"24","messages":"25","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"26","messages":"27","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"28","messages":"29","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/index.tsx",[],"/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/serviceWorker.ts",[],"/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/app/store.ts",[],"/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/App.tsx",[],"/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/app/rootReducer.ts",[],"/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/features/auth/index.ts",[],"/Users/olajohn/Downloads/docs/Copy/Tutorials/fitfam/src/hooks/useLocalStorage.tsx",[]] -------------------------------------------------------------------------------- /noted-client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /noted-client/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the [Redux](https://redux.js.org/) and [Redux Toolkit](https://redux-toolkit.js.org/) template. 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `yarn start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `yarn test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `yarn build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `yarn eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | -------------------------------------------------------------------------------- /noted-client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-fit-fam", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@reduxjs/toolkit": "^1.2.5", 7 | "@testing-library/jest-dom": "^4.2.4", 8 | "@testing-library/react": "^9.3.2", 9 | "@testing-library/user-event": "^7.1.2", 10 | "@types/jest": "^24.0.0", 11 | "@types/node": "^12.0.0", 12 | "@types/react": "^16.9.0", 13 | "@types/react-dom": "^16.9.0", 14 | "@types/react-redux": "^7.1.7", 15 | "react": "^17.0.1", 16 | "react-dom": "^17.0.1", 17 | "react-redux": "^7.2.0", 18 | "react-scripts": "4.0.1", 19 | "typescript": "~3.8.2" 20 | }, 21 | "scripts": { 22 | "start": "react-scripts start", 23 | "build": "react-scripts build", 24 | "test": "react-scripts test", 25 | "eject": "react-scripts eject", 26 | "prettier": "prettier --write \"**/*.{js,tsx,ts,json,yaml,yml}\"", 27 | "prettier:generated": "prettier --write \"src/services/openapi/**/*.ts\"", 28 | "types:openapi": "openapi -i http://localhost:3000/api-json -o src/services/openapi --useUnionTypes && yarn prettier:generated" 29 | }, 30 | "eslintConfig": { 31 | "extends": "react-app" 32 | }, 33 | "browserslist": { 34 | "production": [ 35 | ">0.2%", 36 | "not dead", 37 | "not op_mini all" 38 | ], 39 | "development": [ 40 | "last 1 chrome version", 41 | "last 1 firefox version", 42 | "last 1 safari version" 43 | ] 44 | }, 45 | "devDependencies": { 46 | "openapi-typescript": "^3.0.1", 47 | "openapi-typescript-codegen": "^0.8.1" 48 | } 49 | } -------------------------------------------------------------------------------- /noted-client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LogRocket-Tutorials/OpenAPI/5a5f3c362d53ed971f904a94123f2eaf8ec35a0c/noted-client/public/favicon.ico -------------------------------------------------------------------------------- /noted-client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React Redux App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /noted-client/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LogRocket-Tutorials/OpenAPI/5a5f3c362d53ed971f904a94123f2eaf8ec35a0c/noted-client/public/logo192.png -------------------------------------------------------------------------------- /noted-client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LogRocket-Tutorials/OpenAPI/5a5f3c362d53ed971f904a94123f2eaf8ec35a0c/noted-client/public/logo512.png -------------------------------------------------------------------------------- /noted-client/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /noted-client/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /noted-client/src/App.css: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@400;700&display=swap'); 2 | 3 | * { 4 | margin: 0; 5 | padding: 0; 6 | box-sizing: border-box; 7 | } 8 | body { 9 | font-family: 'Nunito', sans-serif; 10 | -webkit-font-smoothing: antialiased; 11 | -moz-osx-font-smoothing: grayscale; 12 | color: #fff; 13 | background: #333; 14 | } 15 | 16 | .App { 17 | max-width: 728px; 18 | margin: 4rem auto; 19 | } 20 | 21 | .App > h1 { 22 | text-align: center; 23 | margin: 1rem 0; 24 | } 25 | 26 | .Card { 27 | display: flex; 28 | justify-content: space-between; 29 | align-items: center; 30 | background: #444; 31 | padding: 0.5rem 1rem; 32 | border-bottom: 1px solid #333333; 33 | } 34 | 35 | .Card--text h1 { 36 | color: #ff9900; 37 | } 38 | 39 | .Card--button button { 40 | background: #f5f6f7; 41 | padding: 0.4rem 1rem; 42 | border-radius: 20px; 43 | cursor: pointer; 44 | } 45 | 46 | .Card--button__delete { 47 | border: 1px solid #ca0000; 48 | color: #ca0000; 49 | } 50 | 51 | .Card--button__done { 52 | border: 1px solid #00aa69; 53 | color: #00aa69; 54 | margin-right: 1rem; 55 | } 56 | 57 | .Form { 58 | display: flex; 59 | justify-content: space-between; 60 | align-items: center; 61 | padding: 1rem; 62 | background: #444; 63 | margin-bottom: 1rem; 64 | } 65 | 66 | .Form > div { 67 | display: flex; 68 | justify-content: center; 69 | align-items: center; 70 | } 71 | 72 | .Form input { 73 | background: #f5f6f7; 74 | padding: 0.5rem 1rem; 75 | border: 1px solid #ff9900; 76 | border-radius: 10px; 77 | display: block; 78 | margin: 0.3rem 1rem 0 0; 79 | } 80 | 81 | .Form label { 82 | } 83 | 84 | .Form button { 85 | background: #ff9900; 86 | color: #fff; 87 | padding: 0.5rem 1rem; 88 | border-radius: 20px; 89 | cursor: pointer; 90 | border: none; 91 | } 92 | 93 | .line-through { 94 | text-decoration: line-through; 95 | color: #777 !important; 96 | } 97 | 98 | .hide-button { 99 | display: none; 100 | } 101 | -------------------------------------------------------------------------------- /noted-client/src/App.tsx: -------------------------------------------------------------------------------- 1 | import React, { useCallback, useEffect, useState } from 'react'; 2 | import {AddTodo , TodoItem }from './features/todo'; 3 | import { getTodos, addTodo, updateTodo, deleteTodo } from './services/api/todo'; 4 | import { AddTodoDto, ApiError, EditTodoDto, TodoDto } from './services/openapi'; 5 | 6 | 7 | import './App.css' 8 | 9 | const App = () => { 10 | const [todos, setTodos] = useState([]); 11 | const [error, setError] = useState(); 12 | 13 | const handleSaveTodo=useCallback((e: React.FormEvent, formData: AddTodoDto) =>{ 14 | e.preventDefault(); 15 | addTodo(formData) 16 | .then((todo) => todo) 17 | .catch((err) => setError(err)); 18 | },[]) 19 | 20 | const handleUpdateTodo = useCallback((id: number, todo: EditTodoDto) => { 21 | updateTodo(id, todo) 22 | .then((updatedTodo) => updatedTodo) 23 | .catch((err) => setError(err)); 24 | },[]); 25 | 26 | const handleDeleteTodo = useCallback((id: number) => { 27 | deleteTodo(id).catch((err) => setError(err)); 28 | },[]); 29 | 30 | 31 | useEffect(() => { 32 | getTodos() 33 | .then((allTodos) => setTodos(allTodos)) 34 | .catch((error) => setError(error)); 35 | }, []); 36 | 37 | 38 | return ( 39 |
40 |

My Todos

41 | 42 | {todos.map((todo: TodoDto) => ( 43 | 50 | ))} 51 |
52 | ); 53 | }; 54 | 55 | export default App; 56 | -------------------------------------------------------------------------------- /noted-client/src/app/store.ts: -------------------------------------------------------------------------------- 1 | import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'; 2 | 3 | export const store = configureStore({ 4 | reducer: {}, 5 | }); 6 | 7 | export type RootState = ReturnType; 8 | export type AppThunk = ThunkAction< 9 | ReturnType, 10 | RootState, 11 | unknown, 12 | Action 13 | >; 14 | -------------------------------------------------------------------------------- /noted-client/src/features/todo/AddTodo.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react' 2 | import { AddTodoDto } from '../../services/openapi' 3 | 4 | type Props = { 5 | saveTodo: (e: React.FormEvent, formData: AddTodoDto) => void 6 | } 7 | 8 | const defaultTodo: AddTodoDto = { 9 | title: 'Learn JS', 10 | text: 'Rule the world' 11 | } 12 | const AddTodo: React.FC = ({ saveTodo }) => { 13 | const [formData, setFormData] = useState(defaultTodo) 14 | 15 | const handleForm = (e: React.FormEvent): void => { 16 | setFormData({ 17 | ...formData, 18 | [e.currentTarget.id]: e.currentTarget.value, 19 | }) 20 | } 21 | 22 | return ( 23 |
saveTodo(e, formData)}> 24 |
25 |
26 | 27 | 28 |
29 |
30 | 31 | 32 |
33 |
34 | 35 |
36 | ) 37 | } 38 | 39 | export default AddTodo 40 | -------------------------------------------------------------------------------- /noted-client/src/features/todo/TodoItem.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { EditTodoDto, TodoDto } from '../../services/openapi' 3 | import { ApiError } from '../../services/openapi'; 4 | 5 | 6 | type TodoItemProps = { 7 | deleteTodo: (id: number) => void; 8 | error?: ApiError; 9 | todo: TodoDto; 10 | updateTodo: (id:number,todo: EditTodoDto) => void; 11 | 12 | }; 13 | 14 | const TodoItem = ({ todo, updateTodo, deleteTodo }: TodoItemProps) => { 15 | const checkTodo: string = todo.completed ? `line-through` : ''; 16 | return ( 17 |
18 |
19 |

{todo.text}

20 | {todo.title} 21 |
22 |
23 | 29 | 35 |
36 |
37 | ); 38 | }; 39 | 40 | export default TodoItem; 41 | -------------------------------------------------------------------------------- /noted-client/src/features/todo/index.ts: -------------------------------------------------------------------------------- 1 | export { default as AddTodo } from './AddTodo'; 2 | export { default as TodoItem } from './TodoItem'; 3 | -------------------------------------------------------------------------------- /noted-client/src/hooks/useApi.tsx: -------------------------------------------------------------------------------- 1 | import { useCallback, useState } from 'react' 2 | import { ApiError, OpenAPI } from '../services/openapi' 3 | 4 | export function useApi() { 5 | const [error, setError] = useState(undefined) 6 | const [isLoading, setIsloading] = useState(true) 7 | 8 | OpenAPI.BASE = process.env.REACT_APP_API_ENDPOINT as string 9 | const handleRequest = useCallback(async function (request: Promise) { 10 | setIsloading(true) 11 | try { 12 | const response = await request 13 | setError(undefined) 14 | return response 15 | } catch (error) { 16 | setError(error) 17 | } finally { 18 | setIsloading(true) 19 | } 20 | }, []) 21 | 22 | function dismissError() { 23 | setError(undefined) 24 | } 25 | 26 | return { dismissError, error, isLoading, handleRequest } 27 | } 28 | 29 | export default useApi -------------------------------------------------------------------------------- /noted-client/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /noted-client/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import { store } from './app/store'; 6 | import { Provider } from 'react-redux'; 7 | import * as serviceWorker from './serviceWorker'; 8 | 9 | ReactDOM.render( 10 | 11 | 12 | 13 | 14 | , 15 | document.getElementById('root') 16 | ); 17 | 18 | // If you want your app to work offline and load faster, you can change 19 | // unregister() to register() below. Note this comes with some pitfalls. 20 | // Learn more about service workers: https://bit.ly/CRA-PWA 21 | serviceWorker.unregister(); 22 | -------------------------------------------------------------------------------- /noted-client/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /noted-client/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /noted-client/src/serviceWorker.ts: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | type Config = { 24 | onSuccess?: (registration: ServiceWorkerRegistration) => void; 25 | onUpdate?: (registration: ServiceWorkerRegistration) => void; 26 | }; 27 | 28 | export function register(config?: Config) { 29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 30 | // The URL constructor is available in all browsers that support SW. 31 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 32 | if (publicUrl.origin !== window.location.origin) { 33 | // Our service worker won't work if PUBLIC_URL is on a different origin 34 | // from what our page is served on. This might happen if a CDN is used to 35 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 36 | return; 37 | } 38 | 39 | window.addEventListener('load', () => { 40 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 41 | 42 | if (isLocalhost) { 43 | // This is running on localhost. Let's check if a service worker still exists or not. 44 | checkValidServiceWorker(swUrl, config); 45 | 46 | // Add some additional logging to localhost, pointing developers to the 47 | // service worker/PWA documentation. 48 | navigator.serviceWorker.ready.then(() => { 49 | console.log( 50 | 'This web app is being served cache-first by a service ' + 51 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 52 | ); 53 | }); 54 | } else { 55 | // Is not localhost. Just register service worker 56 | registerValidSW(swUrl, config); 57 | } 58 | }); 59 | } 60 | } 61 | 62 | function registerValidSW(swUrl: string, config?: Config) { 63 | navigator.serviceWorker 64 | .register(swUrl) 65 | .then(registration => { 66 | registration.onupdatefound = () => { 67 | const installingWorker = registration.installing; 68 | if (installingWorker == null) { 69 | return; 70 | } 71 | installingWorker.onstatechange = () => { 72 | if (installingWorker.state === 'installed') { 73 | if (navigator.serviceWorker.controller) { 74 | // At this point, the updated precached content has been fetched, 75 | // but the previous service worker will still serve the older 76 | // content until all client tabs are closed. 77 | console.log( 78 | 'New content is available and will be used when all ' + 79 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 80 | ); 81 | 82 | // Execute callback 83 | if (config && config.onUpdate) { 84 | config.onUpdate(registration); 85 | } 86 | } else { 87 | // At this point, everything has been precached. 88 | // It's the perfect time to display a 89 | // "Content is cached for offline use." message. 90 | console.log('Content is cached for offline use.'); 91 | 92 | // Execute callback 93 | if (config && config.onSuccess) { 94 | config.onSuccess(registration); 95 | } 96 | } 97 | } 98 | }; 99 | }; 100 | }) 101 | .catch(error => { 102 | console.error('Error during service worker registration:', error); 103 | }); 104 | } 105 | 106 | function checkValidServiceWorker(swUrl: string, config?: Config) { 107 | // Check if the service worker can be found. If it can't reload the page. 108 | fetch(swUrl, { 109 | headers: { 'Service-Worker': 'script' }, 110 | }) 111 | .then(response => { 112 | // Ensure service worker exists, and that we really are getting a JS file. 113 | const contentType = response.headers.get('content-type'); 114 | if ( 115 | response.status === 404 || 116 | (contentType != null && contentType.indexOf('javascript') === -1) 117 | ) { 118 | // No service worker found. Probably a different app. Reload the page. 119 | navigator.serviceWorker.ready.then(registration => { 120 | registration.unregister().then(() => { 121 | window.location.reload(); 122 | }); 123 | }); 124 | } else { 125 | // Service worker found. Proceed as normal. 126 | registerValidSW(swUrl, config); 127 | } 128 | }) 129 | .catch(() => { 130 | console.log( 131 | 'No internet connection found. App is running in offline mode.' 132 | ); 133 | }); 134 | } 135 | 136 | export function unregister() { 137 | if ('serviceWorker' in navigator) { 138 | navigator.serviceWorker.ready 139 | .then(registration => { 140 | registration.unregister(); 141 | }) 142 | .catch(error => { 143 | console.error(error.message); 144 | }); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /noted-client/src/services/api/hooks/useTodos.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | export const useTodos = () => { 4 | return ( 5 |
6 | 7 |
8 | ) 9 | } 10 | -------------------------------------------------------------------------------- /noted-client/src/services/api/todo.ts: -------------------------------------------------------------------------------- 1 | import { 2 | AddTodoDto, 3 | EditTodoDto, 4 | OpenAPI, 5 | TodoDto, 6 | TodosService, 7 | } from '../openapi'; 8 | 9 | const { add, edit, findAll, findOne, remove } = TodosService; 10 | 11 | OpenAPI.BASE = 'http://localhost:3000'; 12 | 13 | export const getTodos = async () => { 14 | try { 15 | const todos: TodoDto[] = await findAll(); 16 | return todos; 17 | } catch (error) { 18 | throw new Error(error); 19 | } 20 | }; 21 | 22 | export const getTodoById = async (id: number): Promise => { 23 | try { 24 | return await findOne(id); 25 | } catch (error) { 26 | throw new Error(error); 27 | } 28 | }; 29 | 30 | export const addTodo = async (newTodo: AddTodoDto): Promise => { 31 | try { 32 | return await add(newTodo); 33 | } catch (error) { 34 | throw new Error(error); 35 | } 36 | }; 37 | 38 | export const updateTodo = async ( 39 | id: number, 40 | todo: EditTodoDto 41 | ): Promise => { 42 | try { 43 | return await edit(id, todo); 44 | } catch (error) { 45 | throw new Error(error); 46 | } 47 | }; 48 | 49 | export const deleteTodo = async (id: number) => { 50 | try { 51 | await remove(id); 52 | } catch (error) { 53 | throw new Error(error); 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/core/ApiError.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | import type { ApiResult } from "./ApiResult"; 5 | 6 | export class ApiError extends Error { 7 | public readonly url: string; 8 | public readonly status: number; 9 | public readonly statusText: string; 10 | public readonly body: any; 11 | 12 | constructor(response: ApiResult, message: string) { 13 | super(message); 14 | 15 | this.url = response.url; 16 | this.status = response.status; 17 | this.statusText = response.statusText; 18 | this.body = response.body; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/core/ApiRequestOptions.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | export type ApiRequestOptions = { 5 | readonly method: 6 | | "GET" 7 | | "PUT" 8 | | "POST" 9 | | "DELETE" 10 | | "OPTIONS" 11 | | "HEAD" 12 | | "PATCH"; 13 | readonly path: string; 14 | readonly cookies?: Record; 15 | readonly headers?: Record; 16 | readonly query?: Record; 17 | readonly formData?: Record; 18 | readonly body?: any; 19 | readonly responseHeader?: string; 20 | readonly errors?: Record; 21 | }; 22 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/core/ApiResult.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | export type ApiResult = { 5 | readonly url: string; 6 | readonly ok: boolean; 7 | readonly status: number; 8 | readonly statusText: string; 9 | readonly body: any; 10 | }; 11 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/core/OpenAPI.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | type Resolver = () => Promise; 5 | type Headers = Record; 6 | 7 | type Config = { 8 | BASE: string; 9 | VERSION: string; 10 | WITH_CREDENTIALS: boolean; 11 | TOKEN?: string | Resolver; 12 | USERNAME?: string | Resolver; 13 | PASSWORD?: string | Resolver; 14 | HEADERS?: Headers | Resolver; 15 | }; 16 | 17 | export const OpenAPI: Config = { 18 | BASE: "", 19 | VERSION: "1.0", 20 | WITH_CREDENTIALS: false, 21 | TOKEN: undefined, 22 | USERNAME: undefined, 23 | PASSWORD: undefined, 24 | HEADERS: undefined, 25 | }; 26 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/core/request.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | import { ApiError } from "./ApiError"; 5 | import type { ApiRequestOptions } from "./ApiRequestOptions"; 6 | import type { ApiResult } from "./ApiResult"; 7 | import { OpenAPI } from "./OpenAPI"; 8 | 9 | function isDefined( 10 | value: T | null | undefined 11 | ): value is Exclude { 12 | return value !== undefined && value !== null; 13 | } 14 | 15 | function isString(value: any): value is string { 16 | return typeof value === "string"; 17 | } 18 | 19 | function isStringWithValue(value: any): value is string { 20 | return isString(value) && value !== ""; 21 | } 22 | 23 | function isBlob(value: any): value is Blob { 24 | return value instanceof Blob; 25 | } 26 | 27 | function getQueryString(params: Record): string { 28 | const qs: string[] = []; 29 | Object.keys(params).forEach((key) => { 30 | const value = params[key]; 31 | if (isDefined(value)) { 32 | if (Array.isArray(value)) { 33 | value.forEach((value) => { 34 | qs.push( 35 | `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}` 36 | ); 37 | }); 38 | } else { 39 | qs.push( 40 | `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}` 41 | ); 42 | } 43 | } 44 | }); 45 | if (qs.length > 0) { 46 | return `?${qs.join("&")}`; 47 | } 48 | return ""; 49 | } 50 | 51 | function getUrl(options: ApiRequestOptions): string { 52 | const path = options.path.replace(/[:]/g, "_"); 53 | const url = `${OpenAPI.BASE}${path}`; 54 | 55 | if (options.query) { 56 | return `${url}${getQueryString(options.query)}`; 57 | } 58 | return url; 59 | } 60 | 61 | function getFormData(params: Record): FormData { 62 | const formData = new FormData(); 63 | Object.keys(params).forEach((key) => { 64 | const value = params[key]; 65 | if (isDefined(value)) { 66 | formData.append(key, value); 67 | } 68 | }); 69 | return formData; 70 | } 71 | 72 | type Resolver = () => Promise; 73 | 74 | async function resolve(resolver?: T | Resolver): Promise { 75 | if (typeof resolver === "function") { 76 | return (resolver as Resolver)(); 77 | } 78 | return resolver; 79 | } 80 | 81 | async function getHeaders(options: ApiRequestOptions): Promise { 82 | const headers = new Headers({ 83 | Accept: "application/json", 84 | ...OpenAPI.HEADERS, 85 | ...options.headers, 86 | }); 87 | 88 | const token = await resolve(OpenAPI.TOKEN); 89 | const username = await resolve(OpenAPI.USERNAME); 90 | const password = await resolve(OpenAPI.PASSWORD); 91 | 92 | if (isStringWithValue(token)) { 93 | headers.append("Authorization", `Bearer ${token}`); 94 | } 95 | 96 | if (isStringWithValue(username) && isStringWithValue(password)) { 97 | const credentials = btoa(`${username}:${password}`); 98 | headers.append("Authorization", `Basic ${credentials}`); 99 | } 100 | 101 | if (options.body) { 102 | if (isBlob(options.body)) { 103 | headers.append( 104 | "Content-Type", 105 | options.body.type || "application/octet-stream" 106 | ); 107 | } else if (isString(options.body)) { 108 | headers.append("Content-Type", "text/plain"); 109 | } else { 110 | headers.append("Content-Type", "application/json"); 111 | } 112 | } 113 | return headers; 114 | } 115 | 116 | function getRequestBody(options: ApiRequestOptions): BodyInit | undefined { 117 | if (options.formData) { 118 | return getFormData(options.formData); 119 | } 120 | if (options.body) { 121 | if (isString(options.body) || isBlob(options.body)) { 122 | return options.body; 123 | } else { 124 | return JSON.stringify(options.body); 125 | } 126 | } 127 | return undefined; 128 | } 129 | 130 | async function sendRequest( 131 | options: ApiRequestOptions, 132 | url: string 133 | ): Promise { 134 | const request: RequestInit = { 135 | method: options.method, 136 | headers: await getHeaders(options), 137 | body: getRequestBody(options), 138 | }; 139 | if (OpenAPI.WITH_CREDENTIALS) { 140 | request.credentials = "include"; 141 | } 142 | return await fetch(url, request); 143 | } 144 | 145 | function getResponseHeader( 146 | response: Response, 147 | responseHeader?: string 148 | ): string | null { 149 | if (responseHeader) { 150 | const content = response.headers.get(responseHeader); 151 | if (isString(content)) { 152 | return content; 153 | } 154 | } 155 | return null; 156 | } 157 | 158 | async function getResponseBody(response: Response): Promise { 159 | try { 160 | const contentType = response.headers.get("Content-Type"); 161 | if (contentType) { 162 | const isJSON = contentType.toLowerCase().startsWith("application/json"); 163 | if (isJSON) { 164 | return await response.json(); 165 | } else { 166 | return await response.text(); 167 | } 168 | } 169 | } catch (error) { 170 | console.error(error); 171 | } 172 | return null; 173 | } 174 | 175 | function catchErrors(options: ApiRequestOptions, result: ApiResult): void { 176 | const errors: Record = { 177 | 400: "Bad Request", 178 | 401: "Unauthorized", 179 | 403: "Forbidden", 180 | 404: "Not Found", 181 | 500: "Internal Server Error", 182 | 502: "Bad Gateway", 183 | 503: "Service Unavailable", 184 | ...options.errors, 185 | }; 186 | 187 | const error = errors[result.status]; 188 | if (error) { 189 | throw new ApiError(result, error); 190 | } 191 | 192 | if (!result.ok) { 193 | throw new ApiError(result, "Generic Error"); 194 | } 195 | } 196 | 197 | /** 198 | * Request using fetch client 199 | * @param options The request options from the the service 200 | * @returns ApiResult 201 | * @throws ApiError 202 | */ 203 | export async function request(options: ApiRequestOptions): Promise { 204 | const url = getUrl(options); 205 | const response = await sendRequest(options, url); 206 | const responseBody = await getResponseBody(response); 207 | const responseHeader = getResponseHeader(response, options.responseHeader); 208 | 209 | const result: ApiResult = { 210 | url, 211 | ok: response.ok, 212 | status: response.status, 213 | statusText: response.statusText, 214 | body: responseHeader || responseBody, 215 | }; 216 | 217 | catchErrors(options, result); 218 | return result; 219 | } 220 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/index.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | export { ApiError } from "./core/ApiError"; 5 | export { OpenAPI } from "./core/OpenAPI"; 6 | 7 | export type { AddTodoDto } from "./models/AddTodoDto"; 8 | export type { EditTodoDto } from "./models/EditTodoDto"; 9 | export type { TodoDto } from "./models/TodoDto"; 10 | 11 | export { TodosService } from "./services/TodosService"; 12 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/models/AddTodoDto.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | 5 | export type AddTodoDto = { 6 | title: string; 7 | text: string; 8 | }; 9 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/models/EditTodoDto.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | 5 | export type EditTodoDto = { 6 | title: string; 7 | text: string; 8 | completed: boolean; 9 | }; 10 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/models/TodoDto.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | 5 | export type TodoDto = { 6 | /** 7 | * Auto Generated Id 8 | */ 9 | id: number; 10 | /** 11 | * Title for todo 12 | */ 13 | title: string; 14 | /** 15 | * Body of todo 16 | */ 17 | text: string; 18 | completed: boolean; 19 | }; 20 | -------------------------------------------------------------------------------- /noted-client/src/services/openapi/services/TodosService.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | /* tslint:disable */ 3 | /* eslint-disable */ 4 | import type { AddTodoDto } from '../models/AddTodoDto'; 5 | import type { EditTodoDto } from '../models/EditTodoDto'; 6 | import type { TodoDto } from '../models/TodoDto'; 7 | import { request as __request } from '../core/request'; 8 | 9 | export class TodosService { 10 | public static async findAll(): Promise> { 11 | const result = await __request({ 12 | method: 'GET', 13 | path: `/todos`, 14 | }); 15 | return result.body; 16 | } 17 | 18 | public static async add(requestBody: AddTodoDto): Promise { 19 | const result = await __request({ 20 | method: 'POST', 21 | path: `/todos`, 22 | body: requestBody, 23 | }); 24 | return result.body; 25 | } 26 | 27 | public static async findOne(id: number): Promise { 28 | const result = await __request({ 29 | method: 'GET', 30 | path: `/todos/${id}`, 31 | }); 32 | return result.body; 33 | } 34 | 35 | public static async edit(id: number, requestBody: EditTodoDto): Promise { 36 | const result = await __request({ 37 | method: 'PUT', 38 | path: `/todos/${id}`, 39 | body: requestBody, 40 | }); 41 | return result.body; 42 | } 43 | 44 | public static async remove(id: number): Promise { 45 | const result = await __request({ 46 | method: 'DELETE', 47 | path: `/todos/${id}`, 48 | }); 49 | return result.body; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /noted-client/src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /noted-client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "module": "esnext", 17 | "moduleResolution": "node", 18 | "resolveJsonModule": true, 19 | "isolatedModules": true, 20 | "noEmit": true, 21 | "jsx": "react" 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } 27 | --------------------------------------------------------------------------------