Code Monkey home page Code Monkey logo

janishar / nodejs-backend-architecture-typescript Goto Github PK

View Code? Open in Web Editor NEW
2.6K 60.0 615.0 1.37 MB

Node.js Backend Architecture Typescript - Learn to build a backend server for production ready blogging platform like Medium and FreeCodeCamp. Main Features: Role based, Express.js, Mongoose, Redis, Mongodb, Joi, Docker, JWT, Unit Tests, Integration Tests.

Home Page: https://janisharali.com/blog/design-node-js-backend-architecture-like-a-pro

License: Apache License 2.0

TypeScript 98.37% JavaScript 1.20% Dockerfile 0.43%
nodejs expressjs typescript docker docker-compose medium-article mindorks jest mongodb mongoose

nodejs-backend-architecture-typescript's Introduction


๐ŸŽ‰ Announcement

A new repository based on Nest.js is also available here Modern Backend Development - WhereIsMyMotivation ๐ŸŽŠ


Node.js Backend Architecture Typescript Project

A complete project to build a blogging platform like Medium, and FreeCodeCamp

Docker Compose CI

Note: This is the latest (version 2) of the project. If you are using version 1 then checkout the branch version-1


Project Highlights

  1. Node.js
  2. Express.js
  3. Typescript
  4. Mongoose
  5. Redis
  6. Mongodb
  7. Joi
  8. Unit Tests & Integration Tests
  9. Docker
  10. JWT

About The Project

This project is designed for a production ready environment. It can handle the scale and complexity of a very demanding application. This project is being used by companies like MindOrks, AfterAcademy, and CuriousJr. Apps/Websites having 10+ million usebase.

It is suitable for Web Apps, Mobile Apps, and other API services.

About The Author

You can connect with me here:

Project Instructions

We will learn and build the backend application for a blogging platform. The main focus will be to create a maintainable and highly testable architecture.
Following are the features of this project:

  • This backend is written in Typescript: The type safety at build time and having intellisense for it in the IDE like vscode is unparalleled to productivity. I have found production bug reduced to a significant amount since most of the code vulnerabilities are identified during the build phase itself.
  • Separation of concern principle: Each component has been given a particular role. The role of the components is mutually exclusive. This makes the project easy to be unit tested.
  • Feature encapsulation: The files or components that are related to a particular feature have been grouped unless those components are required in multiple features. This enhances the ability to share code across projects.
  • Centralised Error handling: I have created a framework where all the errors are handled centrally. This reduces the ambiguity in the development when the project grows larger.
  • Centralised Response handling: Similar to Error handling we have a response handling framework. This makes it very convenient to apply a common API response pattern.
  • Mongodb is used through Mongoose: Mongodb fits very well to the node.js application. Being NoSQL, fast, and scalable makes it ideal for modern web applications.
  • Redis Memcache: I have used the redis server for caching the items which does not change frequently. It will boost the performance of our system.
  • Async execution: I have used async/await for the promises and made sure to use the non-blocking version of all the functions with few exceptions.
  • Docker compose has been configured: I have created the Dockerfile to provide the easy deployability without any setup and configurations.
  • Unit test is favored: The tests have been written to test the functions and routes without the need of the database server. Integration tests has also been done but the unit test is favored.
  • A pure backend project: I have experienced that when a backend is developed clubbed with a frontend then in the future it becomes really difficult to scale. We would want to create a separate backend project that servers many websites and mobile apps.

I have also open source a complete blogging website working on this backend project: Goto Repository The repository [React.js Isomorphic Web Application Architecture] has a complete React.js web application implemented for a blogging platform which is using this project as its API server.

3RE Architecture: Router, RouteHandler, ResponseHandler, ErrorHandler


Project Outline: Blogging Platform


Request-Response Handling Schematic Diagram


Learn the concepts used in this project

You can find the complete API documentation here

How to build and run this project

  • Install using Docker Compose [Recommended Method]

    • Clone this repo.
    • Make a copy of .env.example file to .env.
    • Make a copy of keys/private.pem.example file to keys/private.pem.
    • Make a copy of keys/public.pem.example file to keys/public.pem.
    • Make a copy of tests/.env.test.example file to tests/.env.test.
    • Install Docker and Docker Compose. Find Instructions Here.
    • Execute docker-compose up -d in terminal from the repo directory.
    • You will be able to access the api from http://localhost:3000
    • Run Tests: docker exec -t app npm test
    • If having any issue then make sure 3000 port is not occupied else provide a different port in .env file.
    • If having any issue then make sure 27017 port is not occupied else provide a different port in .env file.
  • Run The Tests

    • Install node.js and npm on your local machine.
    • From the root of the project executes in terminal npm install.
    • Use the latest version of node on the local machine if the build fails.
    • To run the tests execute npm test.
  • Install Without Docker [2nd Method]

    • Install MongoDB on your local.
    • Do steps 1 to 5 as listed for Install using Docker Compose.
    • Do steps 1 to 3 as listed for Run The Tests.
    • Create users in MongoDB and seed the data taking reference from the addons/init-mongo.js
    • Change the DB_HOST to localhost in .env and tests/.env.test files.
    • Execute npm start and You will be able to access the API from http://localhost:3000
    • To run the tests execute npm test.
  • Postman APIs Here: addons/postman

Learn Backend Development From Our Videos

Project Directory Structure

โ”œโ”€โ”€ .vscode
โ”‚   โ”œโ”€โ”€ settings.json
โ”‚   โ”œโ”€โ”€ tasks.json
โ”‚   โ””โ”€โ”€ launch.json
โ”œโ”€โ”€ .templates
โ”œโ”€โ”€ src
โ”‚   โ”œโ”€โ”€ server.ts
โ”‚   โ”œโ”€โ”€ app.ts
โ”‚   โ”œโ”€โ”€ config.ts
โ”‚   โ”œโ”€โ”€ auth
โ”‚   โ”‚   โ”œโ”€โ”€ apikey.ts
โ”‚   โ”‚   โ”œโ”€โ”€ authUtils.ts
โ”‚   โ”‚   โ”œโ”€โ”€ authentication.ts
โ”‚   โ”‚   โ”œโ”€โ”€ authorization.ts
โ”‚   โ”‚   โ””โ”€โ”€ schema.ts
โ”‚   โ”œโ”€โ”€ core
โ”‚   โ”‚   โ”œโ”€โ”€ ApiError.ts
โ”‚   โ”‚   โ”œโ”€โ”€ ApiResponse.ts
โ”‚   โ”‚   โ”œโ”€โ”€ JWT.ts
โ”‚   โ”‚   โ”œโ”€โ”€ Logger.ts
โ”‚   โ”‚   โ””โ”€โ”€ utils.ts
โ”‚   โ”œโ”€โ”€ cache
โ”‚   โ”‚ย ย  โ”œโ”€โ”€ index.ts
โ”‚   โ”‚ย ย  โ”œโ”€โ”€ keys.ts
โ”‚   โ”‚ย ย  โ”œโ”€โ”€ query.ts
โ”‚   โ”‚ย ย  โ””โ”€โ”€ repository
โ”‚   โ”‚ย ย      โ”œโ”€โ”€ BlogCache.ts
โ”‚   โ”‚ย ย      โ””โ”€โ”€ BlogsCache.ts
โ”‚   โ”œโ”€โ”€ database
โ”‚   โ”‚   โ”œโ”€โ”€ index.ts
โ”‚   โ”‚   โ”œโ”€โ”€ model
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ ApiKey.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Blog.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Keystore.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Role.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ User.ts
โ”‚   โ”‚   โ””โ”€โ”€ repository
โ”‚   โ”‚       โ”œโ”€โ”€ ApiKeyRepo.ts
โ”‚   โ”‚       โ”œโ”€โ”€ BlogRepo.ts
โ”‚   โ”‚       โ”œโ”€โ”€ KeystoreRepo.ts
โ”‚   โ”‚       โ”œโ”€โ”€ RoleRepo.ts
โ”‚   โ”‚       โ””โ”€โ”€ UserRepo.ts
โ”‚   โ”œโ”€โ”€ helpers
โ”‚   โ”‚   โ”œโ”€โ”€ asyncHandler.ts
โ”‚   โ”‚   โ”œโ”€โ”€ permission.ts
โ”‚   โ”‚   โ”œโ”€โ”€ role.ts
โ”‚   โ”‚   โ”œโ”€โ”€ security.ts
โ”‚   โ”‚   โ”œโ”€โ”€ utils.ts
โ”‚   โ”‚   โ””โ”€โ”€ validator.ts
โ”‚   โ”œโ”€โ”€ routes
โ”‚   โ”‚   โ”œโ”€โ”€ access
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ credential.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ login.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ logout.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ schema.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ signup.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ token.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ utils.ts
โ”‚   โ”‚   โ”œโ”€โ”€ blog
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ editor.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ index.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ schema.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ writer.ts
โ”‚   โ”‚ย ย  โ”œโ”€โ”€ blogs
โ”‚   โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ index.ts
โ”‚   โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ schema.ts
โ”‚   โ”‚   โ”œโ”€โ”€ index.ts
โ”‚   โ”‚   โ””โ”€โ”€ profile
โ”‚   โ”‚       โ”œโ”€โ”€ schema.ts
โ”‚   โ”‚       โ””โ”€โ”€ user.ts
โ”‚   โ””โ”€โ”€ types
โ”‚       โ””โ”€โ”€ app-request.d.ts
โ”œโ”€โ”€ tests
โ”‚   โ”œโ”€โ”€ auth
โ”‚   โ”‚   โ”œโ”€โ”€ apikey
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ mock.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ unit.test.ts
โ”‚   โ”‚   โ”œโ”€โ”€ authUtils
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ mock.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ unit.test.ts
โ”‚   โ”‚   โ”œโ”€โ”€ authentication
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ mock.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ unit.test.ts
โ”‚   โ”‚   โ””โ”€โ”€ authorization
โ”‚   โ”‚       โ”œโ”€โ”€ mock.ts
โ”‚   โ”‚       โ””โ”€โ”€ unit.test.ts
โ”‚   โ”œโ”€โ”€ core
โ”‚   โ”‚   โ””โ”€โ”€ jwt
โ”‚   โ”‚       โ”œโ”€โ”€ mock.ts
โ”‚   โ”‚       โ””โ”€โ”€ unit.test.ts
โ”‚   โ”œโ”€โ”€ cache
โ”‚   โ”‚   โ””โ”€โ”€ mock.ts
โ”‚   โ”œโ”€โ”€ database
โ”‚   โ”‚   โ””โ”€โ”€ mock.ts
โ”‚   โ”œโ”€โ”€ routes
โ”‚   โ”‚   โ”œโ”€โ”€ access
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ login
โ”‚   โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ integration.test.ts
โ”‚   โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ mock.ts
โ”‚   โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ unit.test.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ signup
โ”‚   โ”‚   โ”‚       โ”œโ”€โ”€ mock.ts
โ”‚   โ”‚   โ”‚       โ””โ”€โ”€ unit.test.ts
โ”‚   โ”‚   โ””โ”€โ”€ blog
โ”‚   โ”‚       โ”œโ”€โ”€ index
โ”‚   โ”‚       โ”‚   โ”œโ”€โ”€ mock.ts
โ”‚   โ”‚       โ”‚   โ””โ”€โ”€ unit.test.ts
โ”‚   โ”‚       โ””โ”€โ”€ writer
โ”‚   โ”‚           โ”œโ”€โ”€ mock.ts
โ”‚   โ”‚           โ””โ”€โ”€ unit.test.ts
โ”‚   โ”œโ”€โ”€ .env.test
โ”‚   โ””โ”€โ”€ setup.ts
โ”œโ”€โ”€ addons
โ”‚   โ””โ”€โ”€ init-mongo.js
โ”œโ”€โ”€ keys
โ”‚   โ”œโ”€โ”€ private.pem
โ”‚   โ””โ”€โ”€ public.pem
โ”œโ”€โ”€ .env
โ”œโ”€โ”€ .gitignore
โ”œโ”€โ”€ .dockerignore
โ”œโ”€โ”€ .eslintrc
โ”œโ”€โ”€ .eslintignore
โ”œโ”€โ”€ .prettierrc
โ”œโ”€โ”€ .prettierignore
โ”œโ”€โ”€ .travis.yml
โ”œโ”€โ”€ Dockerfile
โ”œโ”€โ”€ docker-compose.yml
โ”œโ”€โ”€ package-lock.json
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ jest.config.js
โ””โ”€โ”€ tsconfig.json

Directory Traversal for Signup API call

/src โ†’ server.ts โ†’ app.ts โ†’ /routes/index.ts โ†’ /auth/apikey.ts โ†’ schema.ts โ†’ /helpers/validator.ts โ†’ asyncHandler.ts โ†’ /routes/access/signup.ts โ†’ schema.ts โ†’ /helpers/validator.ts โ†’ asyncHandler.ts โ†’ /database/repository/UserRepo.ts โ†’ /database/model/User.ts โ†’ /core/ApiResponses.ts

API Examples

  • Signup
    • Method and Headers
    POST /signup/basic HTTP/1.1
    Host: localhost:3000
    x-api-key: GCMUDiuY5a7WvyUNt9n3QztToSHzK7Uj
    Content-Type: application/json
    
    • Request Body
    {
        "name" : "Janishar Ali",
        "email": "[email protected]",
        "password": "changeit",
        "profilePicUrl": "https://avatars1.githubusercontent.com/u/11065002?s=460&u=1e8e42bda7e6f579a2b216767b2ed986619bbf78&v=4"
    }
    • Response Body: 200
    {
      "statusCode": "10000",
      "message": "Signup Successful",
      "data": {
        "user": {
          "_id": "63a19e5ba2730d1599d46c0b",
          "name": "Janishar Ali",
          "roles": [
             {
               "_id": "63a197b39e07f859826e6626",
               "code": "LEARNER",
               "status": true
             }
            ],
          "profilePicUrl": "https://avatars1.githubusercontent.com/u/11065002?s=460&u=1e8e42bda7e6f579a2b216767b2ed986619bbf78&v=4"
        },
        "tokens": {
          "accessToken": "some_token",
          "refreshToken": "some_token"
        }
      }
    }
    • Response Body: 400
    {
      "statusCode": "10001",
      "message": "Bad Parameters"
    }
  • Profile Private
    • Method and Headers
    GET /profile/my HTTP/1.1
    Host: localhost:3000
    x-api-key: GCMUDiuY5a7WvyUNt9n3QztToSHzK7Uj
    Content-Type: application/json
    Authorization: Bearer <your_token_received_from_signup_or_login>
    
    • Response Body: 200
    {
      "statusCode": "10000",
      "message": "success",
      "data": {
        "name": "Janishar Ali Anwar",
        "profilePicUrl": "https://avatars1.githubusercontent.com/u/11065002?s=460&u=1e8e42bda7e6f579a2b216767b2ed986619bbf78&v=4",
        "roles": [
          {
            "_id": "5e7b8acad7aded2407e078d7",
            "code": "LEARNER"
          },
          {
            "_id": "5e7b8c22d347fc2407c564a6",
            "code": "WRITER"
          },
          {
            "_id": "5e7b8c2ad347fc2407c564a7",
            "code": "EDITOR"
          }
        ]
      }
    }

Find this project useful ? โค๏ธ

  • Support it by clicking the โญ button on the upper right of this page. โœŒ๏ธ

License

   Copyright (C) 2024 JANISHAR ALI ANWAR

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

nodejs-backend-architecture-typescript's People

Contributors

janishar avatar kafiln avatar

Stargazers

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

Watchers

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

nodejs-backend-architecture-typescript's Issues

Issue with typeorm integration

Want to use an ORM approach for all types of DB as backend so using Typeorm for typescript. Can we have a pattern of model in that way.?

after starting the docker image getting the error

getting error

[email protected] start /home/node/app

node -r dotenv/config build/server.js

internal/modules/cjs/loader.js:965
throw err;
^

Error: Cannot find module '/home/node/app/build/server.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:962:15)
at Function.Module._load (internal/modules/cjs/loader.js:838:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}

Issue using Mongoose 5.12

Hi,

I tried to bump mongoose to 5.12 but I'm a newbie and I can't do it right.

I continue to have compiling errors like this :

Type 'LeanDocument' is missing the following properties from type 'Blog': $getAllSubdocs, $ignore, $isDefault, $isDeleted, and 48 more.ts(2740)
Type 'Promise' is not assignable to type 'Promise<Blog[]>'.
Type 'Blog' is missing the following properties from type 'Blog[]': length, pop, push, concat, and 28 more.ts(2322)

Could someone eventually check and propose a fix?

Regards

tslint.json not found

The tslint script specifies the use of tslint.json file for configuration but it is absent in the repository.

[Issue] Can't pass integration test

Hello and thank you for your amazing work.

I have read the README and followed all the instructions but I can't seem the make the integration.test.ts pass !

It seems like it's not connected to the DB so it can't create a user nor an apiKey, which make all the tests related to it throw error like

TypeError: Cannot read property 'key' of null

Any idea why is this happening ? Am I missing something ?

Thank you ๐Ÿ‘

[security]: Flaw in implementation of `refresh-token`

The idea of sending refresh-token is to send a 'SECRET' key which can then track down the user from the keystore. So, the refresh-token, should return a key of some sort (maybe generated by crypto module) instead of JWT. This was brought forward by Auth0, the parent organisation of JWT. I would like to create a PR regarding this. Ping me if you think this idea is good enough ๐Ÿค”.

[ Discussion - important ]

  1. access > token.ts | line : 3 (import { ProtectedRequest } from 'app-request';)
    Q: - from where you are importing as there is nothing as "app-request" in package.json

  2. how you pass "'x-access-token'" as your postman file has an Authorization header (https://documenter.getpostman.com/view/1552895/SzYUZg52?version=latest#3eb6d8e6-b3a7-455b-b60f-d92bfa13992f).

I was trying to run your code but it gave me an error so I do a modification > added x-access-token in the header and put access token removing "Bearer ". it is working.

Q:- I didn't find any code block where the Authorization header is cloning the value in x-access-token. I may be wrong.

I would like to hear from you. Thank you for sharing such a great code-bock. really don't know how? But my skeleton(I called it) of the maximum projects is similar with your coding pattern (around 60%). the only difference is I didn't use @hapi/joi and typescript. I am making another skeleton where I want to implement the idea of your logger+ @hapi/joi + few more thing.

[bug]: Wrong indexing in the schema

The KeyStore schema uses multiple indexing which only works if you are using those individual fields to query in the db. So, findforKey and find in src/database/repository/KeystoreRepo.ts will not use the index currently defined.

Inorder to fix this, you need to make two indexes:

  1. For findforKey which uses compound indexing { client: 1, primaryKey: 1 }
  2. For find which uses compound indexing { client: 1, primaryKey: 1, secondaryKey: 1 }

This is how the Keystore schema should have been indexed.

I am willing to create a pull a request for this change. Please acknowledge. ๐Ÿ˜ƒ

Config sec to days

I think this needs to change in config:

from:
export const tokenInfo = {
accessTokenValidityDays: parseInt(process.env.ACCESS_TOKEN_VALIDITY_SEC || '0'),
refreshTokenValidityDays: parseInt(process.env.REFRESH_TOKEN_VALIDITY_SEC || '0'),
issuer: process.env.TOKEN_ISSUER || '',
audience: process.env.TOKEN_AUDIENCE || '',
};

to:
export const tokenInfo = {
accessTokenValidityDays: parseInt(process.env.ACCESS_TOKEN_VALIDITY_DAYS || '0'),
refreshTokenValidityDays: parseInt(process.env.REFRESH_TOKEN_VALIDITY_DAYS || '0'),
issuer: process.env.TOKEN_ISSUER || '',
audience: process.env.TOKEN_AUDIENCE || '',
};

Argument of type '(req: ProtectedRequest, res: Response<any>, next: NextFunction) => Promise<void>' is not assignable to parameter of type 'AsyncFunction'

I customized type of request in app-request file. But when I call type of requests, my typescript get error and I do not know reason. I try to fix but not. Here error:

Argument of type '(req: ProtectedRequest, res: Response<any>, next: NextFunction) => Promise<void>' is not assignable to parameter of type 'AsyncFunction'

signup.ts

import express from 'express';
import { SuccessResponse } from '../../../middleware/ApiResponse';
import UserRepo from '../../../database/repository/UserRepo';
import User from '../../../database/model/User';
import validator from '../../../helpers/validator';
import asyncHandler from '../../../helpers/asyncHandler';
import { BadRequestError } from '../../../middleware/ApiError';
import bcrypt from 'bcrypt';
import schema from './schema';
import _ from 'lodash';
import { PublishRequest } from 'app-request';

const router = express.Router();

router.post(
  '',
  validator(schema.signup),
  asyncHandler(async (req: PublishRequest, res) => {
    const user = await UserRepo.findByEmail(req.body.email);
    if (user) throw new BadRequestError('User already registered');

    const passwordHash = await bcrypt.hash(req.body.password, 10);

    const { user: createdUser } = await UserRepo.create(
      {
        fullname: req.body.fullname,
        username: req.body.username,
        phone: req.body.phone,
        email: req.body.email,
        profilePicUrl: req.body.profilePicUrl,
        password: passwordHash,
      } as User
    );

    new SuccessResponse('Signup Successful', {
      user: _.pick(createdUser, ['_id', 'fullname', 'name', 'phone', 'email', 'profilePicUrl'])
    }).send(res);
  }),
);

export default router;

app-request.d.ts

import { Request } from 'express';
import User from '../database/model/User';
import Keystore from '../database/model/Keystore';

declare interface PublicRequest extends Request {
  apiKey: string;
}

declare interface ProtectedRequest extends Request {
  user: User;
  accessToken: string;
  keystore: Keystore;
}

declare interface Tokens {
  accessToken: string;
  refreshToken: string;
}

Please help me fix it. Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.