├── .gitignore ├── README.md ├── back-end ├── .eslintrc.js ├── .prettierrc ├── README.md ├── data │ └── .gitkeep ├── nest-cli.json ├── package.json ├── schema.gql ├── src │ ├── app.controller.spec.ts │ ├── app.controller.ts │ ├── app.module.ts │ ├── app.service.ts │ ├── config │ │ └── orm.ts │ ├── db │ │ ├── loaders │ │ │ ├── UserLoader.ts │ │ │ └── index.ts │ │ ├── migrations │ │ │ ├── 1585025619325-create-users.ts │ │ │ └── 1585025829086-create-messages.ts │ │ └── models │ │ │ ├── message.entity.ts │ │ │ └── user.entity.ts │ ├── main.ts │ ├── repo.module.ts │ ├── repo.service.ts │ └── resolvers │ │ ├── input │ │ ├── message.input.ts │ │ └── user.input.ts │ │ ├── message.resolver.ts │ │ └── user.resolver.ts ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock └── front-end ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.tsx ├── index.tsx ├── pages │ ├── Board │ │ ├── index.tsx │ │ └── styles.ts │ └── Home │ │ ├── index.tsx │ │ └── styles.ts ├── react-app-env.d.ts ├── routes.tsx ├── services │ ├── api.ts │ └── history.tsx └── styles │ └── global.ts ├── tsconfig.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | back-end/data/*.db 2 | 3 | **/node_modules 4 | **/dist 5 | 6 | .env 7 | 8 | yarn-error.log -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Code Challenge - NestJS + TypeORM + GraphQL 3 |

4 | 5 |

Simple GraphQL API with NestJS in Back-end. React and Apollo Client for Front-end.

6 | 7 |

8 | 9 | Contributors 10 | 11 | 12 | License 13 | 14 |

15 | 16 |
17 | 18 | ## Participants 19 | 20 | | [](https://github.com/guilhermerodz) | 21 | | :------------------------------------------------------------------------------------------------------------------------: | 22 | 23 | 24 | | [Guilherme Rodz](https://github.com/guilhermerodz) 25 | 26 | ## Functional Requirements 27 | 28 | - [x] User register with e-mail only 29 | - [x] User login with e-mail only 30 | - [x] User need to be able to post messages on the Board (Back-end) 31 | - [ ] User need to be able to post messages on the Board (Front-end) 32 | - [x] (optional) User need to be able to delete messages (Back-end) 33 | - [ ] (optional) User need to be able to delete messages (Front-end) 34 | - [x] New messages can be listed at real time (Back-end) 35 | - [ ] New messages can be listed at real time (Front-end) 36 | - [ ] Add Swagger support 37 | - [ ] DataLoader integration 38 | 39 | ## Business Rules 40 | 41 | - [x] Message can only be deleted by its author 42 | 43 | ## Non-functional Requirements 44 | 45 | - [x] Nest.js 46 | - [x] GraphQL 47 | - [x] TypeORM 48 | - [x] React + Apollo Client (or another library) 49 | 50 | ## What can be better? 51 | 52 | - User ID could be stored at Context API in Front-end; 53 | 54 | ## Dependencies 55 | 56 | - [Node](https://nodejs.org/en/) = 10 57 | 58 | ## Getting started 59 | 60 | 1. Clone this repository;
61 | 2. Run `npm or yarn install` at each project in order to install dependencies.
62 | 3. Run `yarn start:dev` for `back-end` and `yarn start` for `front-end` folder.
63 | 4. Access `localhost:3000` in your browser. GraphQL playground: `localhost:3333/graphql`.
64 | 65 | ## Contributing 66 | 67 | Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests. 68 | -------------------------------------------------------------------------------- /back-end/.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 | -------------------------------------------------------------------------------- /back-end/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /back-end/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 | -------------------------------------------------------------------------------- /back-end/data/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rocketseat-content/youtube-challenge-nestjs-graphql/a245c1c7a44dcf2aa4058f3e94b3f7289c07e61b/back-end/data/.gitkeep -------------------------------------------------------------------------------- /back-end/nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /back-end/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "back-end", 3 | "author": { 4 | "name": "Guilherme Rodz" 5 | }, 6 | "version": "0.0.1", 7 | "description": "", 8 | "private": true, 9 | "license": "UNLICENSED", 10 | "scripts": { 11 | "prebuild": "rimraf dist", 12 | "build": "nest build", 13 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 14 | "start": "nest start", 15 | "start:dev": "nest start --watch", 16 | "start:debug": "nest start --debug --watch", 17 | "start:prod": "node dist/main", 18 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 19 | "test": "jest", 20 | "test:watch": "jest --watch", 21 | "test:cov": "jest --coverage", 22 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 23 | "test:e2e": "jest --config ./test/jest-e2e.json", 24 | "typeorm": "ts-node ./node_modules/typeorm/cli.js --config src/config/orm.ts" 25 | }, 26 | "dependencies": { 27 | "@nestjs/common": "^7.0.0", 28 | "@nestjs/core": "^7.0.0", 29 | "@nestjs/graphql": "^7.0.14", 30 | "@nestjs/platform-express": "^7.0.0", 31 | "@nestjs/typeorm": "^7.0.0", 32 | "@types/graphql": "^14.5.0", 33 | "apollo-server-express": "^2.11.0", 34 | "dataloader": "^2.0.0", 35 | "graphql": "^14.6.0", 36 | "graphql-subscriptions": "^1.1.0", 37 | "graphql-tools": "^4.0.7", 38 | "reflect-metadata": "^0.1.13", 39 | "rimraf": "^3.0.2", 40 | "rxjs": "^6.5.4", 41 | "sqlite3": "^4.1.1", 42 | "type-graphql": "^0.17.6", 43 | "typeorm": "^0.2.24", 44 | "voyager": "^0.4.13" 45 | }, 46 | "devDependencies": { 47 | "@nestjs/cli": "^7.0.0", 48 | "@nestjs/schematics": "^7.0.0", 49 | "@nestjs/testing": "^7.0.0", 50 | "@types/express": "^4.17.3", 51 | "@types/jest": "25.1.4", 52 | "@types/node": "^13.9.1", 53 | "@types/supertest": "^2.0.8", 54 | "@typescript-eslint/eslint-plugin": "^2.23.0", 55 | "@typescript-eslint/parser": "^2.23.0", 56 | "eslint": "^6.8.0", 57 | "eslint-config-prettier": "^6.10.0", 58 | "eslint-plugin-import": "^2.20.1", 59 | "jest": "^25.1.0", 60 | "prettier": "^1.19.1", 61 | "supertest": "^4.0.2", 62 | "ts-jest": "25.2.1", 63 | "ts-loader": "^6.2.1", 64 | "ts-node": "^8.6.2", 65 | "tsconfig-paths": "^3.9.0", 66 | "typescript": "^3.7.4" 67 | }, 68 | "jest": { 69 | "moduleFileExtensions": [ 70 | "js", 71 | "json", 72 | "ts" 73 | ], 74 | "rootDir": "src", 75 | "testRegex": ".spec.ts$", 76 | "transform": { 77 | "^.+\\.(t|j)s$": "ts-jest" 78 | }, 79 | "coverageDirectory": "../coverage", 80 | "testEnvironment": "node" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /back-end/schema.gql: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------ 2 | # THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY) 3 | # ------------------------------------------------------ 4 | 5 | """ 6 | A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date-time format. 7 | """ 8 | scalar DateTime 9 | 10 | input DeleteMessageInput { 11 | id: Float! 12 | userId: Float! 13 | } 14 | 15 | type Message { 16 | id: Float! 17 | userId: Float! 18 | content: String! 19 | createdAt: DateTime! 20 | updatedAt: DateTime! 21 | user: User! 22 | } 23 | 24 | input MessageInput { 25 | content: String! 26 | userId: Float! 27 | } 28 | 29 | type Mutation { 30 | createOrLoginUser(data: UserInput!): User! 31 | createMessage(data: MessageInput!): Message! 32 | deleteMessage(data: DeleteMessageInput!): Message! 33 | } 34 | 35 | type Query { 36 | getUsers: [User!]! 37 | getUser(id: Float!): User 38 | getMessages: [Message!]! 39 | getMessagesFromUser(userId: Float!): [Message!]! 40 | getMessage(id: Float!): Message 41 | } 42 | 43 | type Subscription { 44 | messageAdded: Message! 45 | } 46 | 47 | type User { 48 | id: Float! 49 | email: String! 50 | createdAt: DateTime! 51 | updatedAt: DateTime! 52 | } 53 | 54 | input UserInput { 55 | email: String! 56 | } 57 | -------------------------------------------------------------------------------- /back-end/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 | -------------------------------------------------------------------------------- /back-end/src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import RepoService from './repo.service'; 3 | 4 | @Controller() 5 | export class AppController { 6 | constructor(private readonly repoService: RepoService) {} 7 | 8 | @Get() 9 | async getHello(): Promise { 10 | return `There are ${await this.repoService.messageRepo.count()} existent messages`; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /back-end/src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { GraphQLModule } from '@nestjs/graphql'; 4 | 5 | import { AppController } from './app.controller'; 6 | import { AppService } from './app.service'; 7 | import * as ormOptions from './config/orm'; 8 | import RepoModule from './repo.module'; 9 | import UserResolver from './resolvers/user.resolver'; 10 | import MessageResolver from './resolvers/message.resolver'; 11 | import { context } from './db/loaders'; 12 | 13 | const gqlImports = [UserResolver, MessageResolver]; 14 | 15 | @Module({ 16 | imports: [ 17 | TypeOrmModule.forRoot(ormOptions), 18 | RepoModule, 19 | ...gqlImports, 20 | GraphQLModule.forRoot({ 21 | autoSchemaFile: 'schema.gql', 22 | playground: true, 23 | installSubscriptionHandlers: true, 24 | context, 25 | }), 26 | ], 27 | controllers: [AppController], 28 | providers: [AppService], 29 | }) 30 | export class AppModule {} 31 | -------------------------------------------------------------------------------- /back-end/src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class AppService { 5 | getHello(): string { 6 | return 'Hello World!'; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /back-end/src/config/orm.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | import { TypeOrmModuleOptions } from '@nestjs/typeorm'; 3 | 4 | const options: TypeOrmModuleOptions = { 5 | type: 'sqlite', 6 | database: 'data/rocketseat.db', 7 | logging: true, 8 | entities: [path.resolve(__dirname, '..', 'db', 'models', '*')], 9 | migrations: [path.resolve(__dirname, '..', 'db', 'migrations', '*')], 10 | }; 11 | 12 | module.exports = options; 13 | -------------------------------------------------------------------------------- /back-end/src/db/loaders/UserLoader.ts: -------------------------------------------------------------------------------- 1 | import * as DataLoader from 'dataloader'; 2 | import { getRepository } from 'typeorm'; 3 | 4 | import User from '../models/user.entity'; 5 | 6 | const batchUsers = async (userIds: number[]) => { 7 | const users = await getRepository(User).findByIds(userIds); 8 | 9 | const userIdMap: { [userId: number]: User } = {}; 10 | 11 | users.forEach(user => { 12 | userIdMap[user.id] = user; 13 | }); 14 | 15 | return userIds.map(userId => userIdMap[userId]); 16 | }; 17 | 18 | export default () => new DataLoader(batchUsers); 19 | -------------------------------------------------------------------------------- /back-end/src/db/loaders/index.ts: -------------------------------------------------------------------------------- 1 | import UserLoader from './UserLoader'; 2 | 3 | export const context = { 4 | UserLoader: UserLoader(), 5 | }; 6 | -------------------------------------------------------------------------------- /back-end/src/db/migrations/1585025619325-create-users.ts: -------------------------------------------------------------------------------- 1 | import { MigrationInterface, QueryRunner, Table } from 'typeorm'; 2 | 3 | export class createUsers1585025619325 implements MigrationInterface { 4 | private table = new Table({ 5 | name: 'users', 6 | columns: [ 7 | { 8 | name: 'id', 9 | type: 'integer', 10 | isPrimary: true, 11 | isGenerated: true, // Auto-increment 12 | generationStrategy: 'increment', 13 | }, 14 | { 15 | name: 'email', 16 | type: 'varchar', 17 | length: '255', 18 | isUnique: true, 19 | isNullable: false, 20 | }, 21 | { 22 | name: 'created_at', 23 | type: 'timestamptz', 24 | isNullable: false, 25 | default: 'now()', 26 | }, 27 | { 28 | name: 'updated_at', 29 | type: 'timestamptz', 30 | isNullable: false, 31 | default: 'now()', 32 | }, 33 | ], 34 | }); 35 | 36 | public async up(queryRunner: QueryRunner): Promise { 37 | await queryRunner.createTable(this.table); 38 | } 39 | public async down(queryRunner: QueryRunner): Promise { 40 | await queryRunner.dropTable(this.table); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /back-end/src/db/migrations/1585025829086-create-messages.ts: -------------------------------------------------------------------------------- 1 | import { 2 | MigrationInterface, 3 | QueryRunner, 4 | Table, 5 | TableForeignKey, 6 | } from 'typeorm'; 7 | 8 | export class createMessages1585025829086 implements MigrationInterface { 9 | private table = new Table({ 10 | name: 'messages', 11 | columns: [ 12 | { 13 | name: 'id', 14 | type: 'integer', 15 | isPrimary: true, 16 | isGenerated: true, // Auto-increment 17 | generationStrategy: 'increment', 18 | }, 19 | { 20 | name: 'user_id', 21 | type: 'integer', 22 | isNullable: false, 23 | }, 24 | { 25 | name: 'content', 26 | type: 'varchar', 27 | length: '255', 28 | isNullable: false, 29 | }, 30 | { 31 | name: 'created_at', 32 | type: 'timestamptz', 33 | isPrimary: false, 34 | isNullable: false, 35 | default: 'now()', 36 | }, 37 | { 38 | name: 'updated_at', 39 | type: 'timestamptz', 40 | isPrimary: false, 41 | isNullable: false, 42 | default: 'now()', 43 | }, 44 | ], 45 | }); 46 | 47 | private foreignKey = new TableForeignKey({ 48 | columnNames: ['user_id'], 49 | referencedColumnNames: ['id'], 50 | onDelete: 'CASCADE', 51 | referencedTableName: 'users', 52 | }); 53 | 54 | public async up(queryRunner: QueryRunner): Promise { 55 | await queryRunner.createTable(this.table); 56 | } 57 | 58 | public async down(queryRunner: QueryRunner): Promise { 59 | await queryRunner.dropTable(this.table); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /back-end/src/db/models/message.entity.ts: -------------------------------------------------------------------------------- 1 | import { Field, ObjectType } from '@nestjs/graphql'; 2 | import { 3 | Entity, 4 | PrimaryGeneratedColumn, 5 | CreateDateColumn, 6 | UpdateDateColumn, 7 | Column, 8 | OneToMany, 9 | JoinColumn, 10 | ManyToOne, 11 | } from 'typeorm'; 12 | import User from './user.entity'; 13 | 14 | @ObjectType() 15 | @Entity({ name: 'messages' }) 16 | export default class Message { 17 | @Field() 18 | @PrimaryGeneratedColumn() 19 | id: number; 20 | 21 | @Field() 22 | @Column({ name: 'user_id' }) 23 | userId: number; 24 | 25 | @Field() 26 | @Column() 27 | content: string; 28 | 29 | @Field() 30 | @CreateDateColumn({ name: 'created_at' }) 31 | createdAt: Date; 32 | 33 | @Field() 34 | @UpdateDateColumn({ name: 'updated_at' }) 35 | updatedAt: Date; 36 | 37 | @Field(() => User) 38 | user: User; 39 | 40 | // Associations 41 | @ManyToOne( 42 | () => User, 43 | user => user.messageConnection, 44 | { primary: true }, 45 | ) 46 | @JoinColumn({ name: 'user_id' }) 47 | userConnection: Promise; 48 | } 49 | -------------------------------------------------------------------------------- /back-end/src/db/models/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { Field, ObjectType } from '@nestjs/graphql'; 2 | import { 3 | Column, 4 | CreateDateColumn, 5 | Entity, 6 | OneToMany, 7 | PrimaryGeneratedColumn, 8 | UpdateDateColumn, 9 | } from 'typeorm'; 10 | import Message from './message.entity'; 11 | 12 | @ObjectType() 13 | @Entity({ name: 'users' }) 14 | export default class User { 15 | @Field() 16 | @PrimaryGeneratedColumn() 17 | id: number; 18 | 19 | @Field() 20 | @Column() 21 | email: string; 22 | 23 | @Field() 24 | @CreateDateColumn({ name: 'created_at' }) 25 | createdAt: Date; 26 | 27 | @Field() 28 | @UpdateDateColumn({ name: 'updated_at' }) 29 | updatedAt: Date; 30 | 31 | // Associations 32 | @OneToMany( 33 | () => Message, 34 | message => message.userConnection, 35 | ) 36 | messageConnection: Promise; 37 | } 38 | -------------------------------------------------------------------------------- /back-end/src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | 4 | async function bootstrap() { 5 | const app = await NestFactory.create(AppModule); 6 | await app.listen(3333); 7 | } 8 | bootstrap(); 9 | -------------------------------------------------------------------------------- /back-end/src/repo.module.ts: -------------------------------------------------------------------------------- 1 | import { Global, Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import RepoService from './repo.service'; 4 | import User from './db/models/user.entity'; 5 | import Message from './db/models/message.entity'; 6 | 7 | @Global() 8 | @Module({ 9 | imports: [TypeOrmModule.forFeature([User, Message])], 10 | providers: [RepoService], 11 | exports: [RepoService], 12 | }) 13 | class RepoModule {} 14 | export default RepoModule; 15 | -------------------------------------------------------------------------------- /back-end/src/repo.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { Repository } from 'typeorm'; 3 | import { InjectRepository } from '@nestjs/typeorm'; 4 | import User from './db/models/user.entity'; 5 | import Message from './db/models/message.entity'; 6 | 7 | @Injectable() 8 | class RepoService { 9 | public constructor( 10 | @InjectRepository(User) public readonly userRepo: Repository, 11 | @InjectRepository(Message) public readonly messageRepo: Repository, 12 | ) {} 13 | } 14 | 15 | export default RepoService; 16 | -------------------------------------------------------------------------------- /back-end/src/resolvers/input/message.input.ts: -------------------------------------------------------------------------------- 1 | import { Field, InputType } from '@nestjs/graphql'; 2 | import UserInput from './user.input'; 3 | 4 | @InputType() 5 | export default class MessageInput { 6 | @Field() 7 | readonly content: string; 8 | 9 | @Field() 10 | readonly userId: number; 11 | } 12 | 13 | @InputType() 14 | export class DeleteMessageInput { 15 | @Field() 16 | readonly id: number; 17 | 18 | @Field() 19 | readonly userId: number; 20 | } 21 | -------------------------------------------------------------------------------- /back-end/src/resolvers/input/user.input.ts: -------------------------------------------------------------------------------- 1 | import { Field, InputType } from '@nestjs/graphql'; 2 | 3 | @InputType() 4 | export default class UserInput { 5 | @Field() 6 | readonly email: string; 7 | } 8 | -------------------------------------------------------------------------------- /back-end/src/resolvers/message.resolver.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Args, 3 | Mutation, 4 | Query, 5 | Resolver, 6 | Parent, 7 | ResolveField, 8 | Subscription, 9 | Context, 10 | } from '@nestjs/graphql'; 11 | import { PubSub } from 'graphql-subscriptions'; 12 | import RepoService from '../repo.service'; 13 | import Message from '../db/models/message.entity'; 14 | import MessageInput, { DeleteMessageInput } from './input/message.input'; 15 | import User from '../db/models/user.entity'; 16 | import { context } from 'src/db/loaders'; 17 | 18 | export const pubSub = new PubSub(); 19 | 20 | @Resolver(() => Message) 21 | export default class MessageResolver { 22 | constructor(private readonly repoService: RepoService) {} 23 | 24 | @Query(() => [Message]) 25 | public async getMessages(): Promise { 26 | return this.repoService.messageRepo.find(); 27 | } 28 | 29 | @Query(() => [Message]) 30 | public async getMessagesFromUser( 31 | @Args('userId') userId: number, 32 | ): Promise { 33 | return this.repoService.messageRepo.find({ 34 | where: { userId }, 35 | }); 36 | } 37 | 38 | @Query(() => Message, { nullable: true }) 39 | public async getMessage(@Args('id') id: number): Promise { 40 | return this.repoService.messageRepo.findOne(id); 41 | } 42 | 43 | @Mutation(() => Message) 44 | public async createMessage( 45 | @Args('data') input: MessageInput, 46 | ): Promise { 47 | const message = this.repoService.messageRepo.create({ 48 | userId: input.userId, 49 | content: input.content, 50 | }); 51 | 52 | const response = await this.repoService.messageRepo.save(message); 53 | 54 | pubSub.publish('messageAdded', { messageAdded: message }); 55 | 56 | return response; 57 | } 58 | 59 | @Mutation(() => Message) 60 | public async deleteMessage( 61 | @Args('data') input: DeleteMessageInput, 62 | ): Promise { 63 | const message = await this.repoService.messageRepo.findOne(input.id); 64 | 65 | if (!message || message.userId !== input.userId) 66 | throw new Error( 67 | 'Message does not exists or you are not the message author', 68 | ); 69 | 70 | const copy = { ...message }; 71 | 72 | await this.repoService.messageRepo.remove(message); 73 | 74 | return copy; 75 | } 76 | 77 | @Subscription(() => Message) 78 | messageAdded() { 79 | return pubSub.asyncIterator('messageAdded'); 80 | } 81 | 82 | @ResolveField(() => User, { name: 'user' }) 83 | public async getUser( 84 | @Parent() parent: Message, 85 | @Context() { UserLoader }: typeof context, 86 | ): Promise { 87 | return UserLoader.load(parent.userId); // With DataLoader 88 | // return this.repoService.userRepo.findOne(parent.userId); // Without DataLoader 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /back-end/src/resolvers/user.resolver.ts: -------------------------------------------------------------------------------- 1 | import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; 2 | import RepoService from '../repo.service'; 3 | import User from '../db/models/user.entity'; 4 | import UserInput from './input/user.input'; 5 | 6 | @Resolver(() => User) 7 | export default class UserResolver { 8 | constructor(private readonly repoService: RepoService) {} 9 | 10 | @Query(() => [User]) 11 | public async getUsers(): Promise { 12 | return this.repoService.userRepo.find(); 13 | } 14 | 15 | @Query(() => User, { nullable: true }) 16 | public async getUser(@Args('id') id: number): Promise { 17 | return this.repoService.userRepo.findOne(id); 18 | } 19 | 20 | @Mutation(() => User) 21 | public async createOrLoginUser( 22 | @Args('data') input: UserInput, 23 | ): Promise { 24 | let user = await this.repoService.userRepo.findOne({ 25 | where: { email: input.email.toLowerCase().trim() }, 26 | }); 27 | 28 | if (!user) { 29 | user = this.repoService.userRepo.create({ 30 | email: input.email.toLowerCase().trim(), 31 | }); 32 | 33 | await this.repoService.userRepo.save(user); 34 | } 35 | 36 | return user; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /back-end/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /back-end/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "target": "es2017", 9 | "sourceMap": true, 10 | "outDir": "./dist", 11 | "baseUrl": "./", 12 | "incremental": true 13 | }, 14 | "exclude": ["node_modules", "dist"] 15 | } 16 | -------------------------------------------------------------------------------- /front-end/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 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 | -------------------------------------------------------------------------------- /front-end/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "front-end", 3 | "author": { 4 | "name": "Guilherme Rodz" 5 | }, 6 | "version": "0.1.0", 7 | "private": true, 8 | "dependencies": { 9 | "@apollo/react-hooks": "^3.1.3", 10 | "@testing-library/jest-dom": "^4.2.4", 11 | "@testing-library/react": "^9.3.2", 12 | "@testing-library/user-event": "^7.1.2", 13 | "@types/jest": "^24.0.0", 14 | "@types/node": "^12.0.0", 15 | "@types/react": "^16.9.0", 16 | "@types/react-dom": "^16.9.0", 17 | "apollo-boost": "^0.4.7", 18 | "apollo-client": "^2.6.8", 19 | "graphql": "^14.6.0", 20 | "graphql-tag": "^2.10.3", 21 | "history": "^4.10.1", 22 | "react": "^16.13.1", 23 | "react-dom": "^16.13.1", 24 | "react-icons": "^3.9.0", 25 | "react-router-dom": "^5.1.2", 26 | "react-scripts": "3.4.1", 27 | "styled-components": "^5.0.1", 28 | "typescript": "~3.7.2" 29 | }, 30 | "scripts": { 31 | "start": "react-scripts start", 32 | "build": "react-scripts build", 33 | "test": "react-scripts test", 34 | "eject": "react-scripts eject" 35 | }, 36 | "eslintConfig": { 37 | "extends": "react-app" 38 | }, 39 | "browserslist": { 40 | "production": [ 41 | ">0.2%", 42 | "not dead", 43 | "not op_mini all" 44 | ], 45 | "development": [ 46 | "last 1 chrome version", 47 | "last 1 firefox version", 48 | "last 1 safari version" 49 | ] 50 | }, 51 | "devDependencies": { 52 | "@types/react-router-dom": "^5.1.3", 53 | "@types/styled-components": "^5.0.1" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /front-end/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rocketseat-content/youtube-challenge-nestjs-graphql/a245c1c7a44dcf2aa4058f3e94b3f7289c07e61b/front-end/public/favicon.ico -------------------------------------------------------------------------------- /front-end/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /front-end/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rocketseat-content/youtube-challenge-nestjs-graphql/a245c1c7a44dcf2aa4058f3e94b3f7289c07e61b/front-end/public/logo192.png -------------------------------------------------------------------------------- /front-end/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rocketseat-content/youtube-challenge-nestjs-graphql/a245c1c7a44dcf2aa4058f3e94b3f7289c07e61b/front-end/public/logo512.png -------------------------------------------------------------------------------- /front-end/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 | -------------------------------------------------------------------------------- /front-end/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /front-end/src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Router } from 'react-router-dom'; 3 | import { ApolloProvider } from '@apollo/react-hooks'; 4 | 5 | import history from './services/history'; 6 | import api from './services/api'; 7 | import Routes from './routes'; 8 | 9 | import GlobalStyles from './styles/global'; 10 | 11 | function App() { 12 | return ( 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | ); 21 | } 22 | 23 | export default App; 24 | -------------------------------------------------------------------------------- /front-end/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | 4 | import App from './App'; 5 | 6 | ReactDOM.render( 7 | 8 | 9 | , 10 | document.getElementById('root') 11 | ); 12 | -------------------------------------------------------------------------------- /front-end/src/pages/Board/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useQuery } from '@apollo/react-hooks'; 3 | import { gql } from 'apollo-boost'; 4 | import { Container, Message } from './styles'; 5 | 6 | interface IMessage { 7 | id: number; 8 | content: string; 9 | user: { 10 | email: string; 11 | }; 12 | } 13 | 14 | const GET_ALL_MESSAGES = gql` 15 | query { 16 | getMessages { 17 | id 18 | content 19 | user { 20 | email 21 | } 22 | } 23 | } 24 | `; 25 | 26 | export default function Board() { 27 | const { loading, data } = useQuery<{ getMessages: IMessage[] }>( 28 | GET_ALL_MESSAGES 29 | ); 30 | 31 | if (loading) return

Loading ...

; 32 | 33 | return ( 34 | 35 | {data?.getMessages.map(item => ( 36 | 37 |

{item.content}

38 | 39 | {item.user.email} 40 |
41 | ))} 42 |
43 | ); 44 | } 45 | -------------------------------------------------------------------------------- /front-end/src/pages/Board/styles.ts: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | export const Container = styled.ul` 4 | margin-top: 5%; 5 | 6 | display: flex; 7 | flex-direction: column; 8 | 9 | align-items: center; 10 | `; 11 | 12 | export const Message = styled.div` 13 | display: flex; 14 | flex-direction: column; 15 | 16 | background: rgba(0, 0, 0, 0.3); 17 | 18 | padding: 20px; 19 | border-radius: 4px; 20 | color: #fff; 21 | 22 | & + div { 23 | margin-top: 20px; 24 | } 25 | 26 | span { 27 | padding-top: 20px; 28 | font-weight: bold; 29 | font-size: 10px; 30 | 31 | opacity: 0.45; 32 | } 33 | `; 34 | -------------------------------------------------------------------------------- /front-end/src/pages/Home/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import { useMutation } from '@apollo/react-hooks'; 3 | import { gql } from 'apollo-boost'; 4 | import { History } from 'history'; 5 | import { FaCheck } from 'react-icons/fa'; 6 | import { Container, Button, Content, Input } from './styles'; 7 | 8 | type Props = { 9 | history: History; 10 | }; 11 | 12 | export const CREATE_OR_LOGIN_USER = gql` 13 | mutation($email: String!) { 14 | createOrLoginUser(data: { email: $email }) { 15 | id 16 | } 17 | } 18 | `; 19 | 20 | const Home: React.FC = ({ history }) => { 21 | const [input, setInput] = useState(''); 22 | 23 | const [createOrLoginUser, { data }] = useMutation(CREATE_OR_LOGIN_USER); 24 | 25 | useEffect(() => { 26 | if (data) { 27 | const { createOrLoginUser } = data; 28 | const { id } = createOrLoginUser; 29 | 30 | history.push(`/dashboard?id=${id}`); 31 | } 32 | }, [data]); 33 | 34 | async function handleRegister(e: React.MouseEvent) { 35 | e.preventDefault(); 36 | 37 | if (input.length < 1) { 38 | alert('Insert a valid e-mail!'); 39 | return; 40 | } 41 | 42 | createOrLoginUser({ variables: { email: input } }); 43 | setInput(''); 44 | } 45 | 46 | return ( 47 | 48 | 49 |
50 | setInput(e.target.value)} 53 | placeholder="E-mail" 54 | /> 55 | 56 | 60 |
61 |
62 |
63 | ); 64 | }; 65 | 66 | export default Home; 67 | -------------------------------------------------------------------------------- /front-end/src/pages/Home/styles.ts: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | export const Container = styled.div` 4 | position: relative; 5 | height: 100vh; 6 | display: flex; 7 | flex-direction: column; 8 | justify-content: space-between; 9 | overflow: hidden; 10 | `; 11 | 12 | export const Content = styled.div` 13 | position: absolute; 14 | top: 50%; 15 | left: 50%; 16 | transform: translate(-50%, -50%); 17 | 18 | form { 19 | display: flex; 20 | flex-direction: column; 21 | } 22 | `; 23 | 24 | export const Button = styled.button` 25 | margin-top: 20px; 26 | 27 | border: none; 28 | min-width: 220px; 29 | padding: 10px; 30 | border-radius: 6px; 31 | background-color: rgba(17, 17, 17, 1); 32 | display: flex; 33 | justify-content: center; 34 | align-items: center; 35 | transition: background-color 0.2s ease-in-out; 36 | span { 37 | margin-left: 10px; 38 | color: #fff; 39 | font-size: 14px; 40 | } 41 | &:hover { 42 | background-color: rgba(17, 17, 17, 0.8); 43 | } 44 | `; 45 | 46 | export const Input = styled.input` 47 | background: transparent; 48 | border: 1px solid #eee; 49 | border-radius: 4px; 50 | padding: 5px 10px; 51 | 52 | color: #fff; 53 | 54 | &::placeholder { 55 | color: #fff; 56 | opacity: 0.3; 57 | } 58 | `; 59 | -------------------------------------------------------------------------------- /front-end/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /front-end/src/routes.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Route, Switch } from 'react-router-dom'; 3 | 4 | import Home from './pages/Home'; 5 | import Board from './pages/Board'; 6 | 7 | export default function Routes() { 8 | return ( 9 | 10 | 11 | 12 | 13 |

404 - Page not found

} /> 14 |
15 | ); 16 | } 17 | -------------------------------------------------------------------------------- /front-end/src/services/api.ts: -------------------------------------------------------------------------------- 1 | import ApolloClient from 'apollo-boost'; 2 | 3 | export default new ApolloClient({ 4 | uri: 'http://localhost:3333/graphql', 5 | // request: (operation) => { 6 | // operation.setContext(({ headers = {} }) => ({ 7 | // headers: { 8 | // ...headers, 9 | // authorization: `Bearer ${bearerToken}`, 10 | // }, 11 | // })); 12 | // }, 13 | }); 14 | -------------------------------------------------------------------------------- /front-end/src/services/history.tsx: -------------------------------------------------------------------------------- 1 | import { createBrowserHistory } from 'history'; 2 | 3 | const history = createBrowserHistory(); 4 | 5 | export default history; 6 | -------------------------------------------------------------------------------- /front-end/src/styles/global.ts: -------------------------------------------------------------------------------- 1 | import { createGlobalStyle } from 'styled-components'; 2 | 3 | export default createGlobalStyle` 4 | @import url('https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap'); 5 | * { 6 | margin: 0; 7 | padding: 0; 8 | outline: none; 9 | box-sizing: border-box; 10 | } 11 | body { 12 | background-color: #282a36; 13 | -webkit-font-smoothing: antialiased; 14 | font: 14px 'Roboto', sans-serif; 15 | } 16 | body, input, button { 17 | font: 14px 'Roboto', sans-serif; 18 | } 19 | a { 20 | text-decoration: none; 21 | } 22 | button { 23 | cursor: pointer; 24 | } 25 | `; 26 | -------------------------------------------------------------------------------- /front-end/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "esModuleInterop": true, 8 | "allowSyntheticDefaultImports": true, 9 | "strict": true, 10 | "forceConsistentCasingInFileNames": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "noEmit": true, 16 | "jsx": "react" 17 | }, 18 | "include": ["src"] 19 | } 20 | --------------------------------------------------------------------------------