1.0.0 • Published 2 years ago

event-ms-api v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

Hubilo Community v2 - Backend Service

Features

  • Multiple environment ready (development, production)
  • Custom email/password user system with basic security and blocking for preventing brute force attacks.
  • Compressed responses.
  • Secured HTTP headers.
  • CORS.
  • Cache (Redis).
  • HTTP request logger in development mode.
  • i18n ready (for sending emails in multiple languages).
  • User roles.
  • Pagination ready.
  • User profile.
  • Users list for admin area.
  • Login access log with IP, browser and country location (for country it looks for the header cf-ipcountry that CloudFlare creates when protecting your website).
  • API autogenerated documentation by Postman.
  • API collection example for Postman.
  • Testing with mocha/chai for API endpoints.
  • NPM scripts for cleaning and seeding the MongoDB database.
  • NPM script for keeping good source code formatting using prettier and ESLint.
  • Use of ESLint for good coding practices.
  • Mailer example with Nodemailer and Mailgun.
  • Ability to refresh token
  • JWT Tokens, make requests with a token after login with Authorization header with value Bearer yourToken where yourToken is the signed and encrypted token given in the response from the login process.

Requirements

  • Node.js 14+
  • MongoDB 4.4+
  • Redis 5.0+

Setting up environments (development or production)

  1. In the root this repository you will find a file named .env.example
  2. Create a new file by copying and pasting the file and then renaming it to just .env
  3. The file .env is already ignored, so you never commit your credentials.
  4. Change the values of the file to your environment (development or production)
  5. Upload the .env to your environment server(development or production)
  6. If you use the postman collection to try the endpoints, change value of the variable server on your environment to the url of your server, for development mode use http://localhost:3000 IMPORTANT: By default token expires in 3 days (4320 minutes set in .env.example). You can refresh token at endpoint GET /token. If everything it´s ok you will get a new token.

i18n

Language is automatically detected from Accept-Language header on the request. So either you send locale manually on the request or your browser will send its default, if Accept-Language header is not sent then it will use en locale as default.

How to run

Database cleaning and seeding samples

There are 3 available commands for this: fresh, clean and seed.

npm run command
  • fresh cleans and then seeds the database with dynamic data.
  • clean cleans the database.
  • seed seeds the database with dynamic data.

Running in development mode (lifting API server)

npm run start

You will know server is running by checking the output of the command npm run dev

****************************
*    Starting Server
*    Port: 3000
*    NODE_ENV: development
*    Database: MongoDB
*    DB Connection: OK
****************************

Running tests

It´s a good practice to do tests at your code, so a sample of how to do that in mocha/chai is also included in the /test directory

npm run test

Formatting code

Format your code with prettier by typing:

npm run format

Formatting markdown files

Format all your markdown files with remark by typing:

npm run remark

Linting code

Lint your code with ESLint by typing:

npm run lint

Usage

Once everything is set up to test API routes either use Postman or any other api testing application. Default username/password combination for login is admin@admin.com/12345.

Postman API example collection

You can import the example collection to Postman. To import, click the import button located and select postman-example.json located within the root directory. Go to manage environments to create environments for development, production, etc. On each of the environments you create you will need to: 1. Create a new key authToken and within the /login request this value is automatically updated after a successfull login through a script located in the tests tab. Each time you make a request to the API it will send Authorization header with the token value in the request, you can check this on the headers of users or cities endpoints in the Postman example. 2. Create a second key server with the url of your server, for development mode use http://localhost:3000 This is a REST API, so it works using the following HTTP methods:

  • GET (Read): Gets a list of items, or a single item
  • POST (Create): Creates an item
  • PATCH (Update): Updates an item
  • DELETE: Deletes an item

Creating new Module (not Model)

Create the a folder with module name under api folder

Now create all module related files under the newly created module folder. --src | --api | --Module Name |-- {module}.model.ts (data model file) |-- {module}.interface.ts (data model interface) |-- {module}.services.ts (CRUD data services, like getUser, updateuser) |-- {module}.utils.ts (Utility file, create if any utility required) |-- {module}.validator.ts (route middleware validator) |-- {module}.controller.ts (Controller functions) |-- {module}.route.ts (routes for the Module)

Creating new sql data Model

  • Add {{module}}.sql.model.ts file in src/api/
  • Run following command to create db migration. npm run migration:create --name create-column-abc
  • Make sure you add create statement in up and drop statement in down script of migration file.

  • Run the db migration command after this, always mention the env as development shown below. npm run migration:run

Updating sql data Model

  • Run following command to create db migration for update table. npm run migration:create --name 'update-{{module}}-{{add/remove/update}}-{{fieldname or the action}}'
  • Make sure you add addColumn/removeColumn/renameColumn statement in up and drop statement in down script of migration file.
  • Run the db migration command after this, always mention the env as development shown below. npm run migration:run

To run the docker image in local, install below depedency

docker docker-compose

cmd to start all the containers at the same time (detached mode)

docker-compose up -d

cmd to start all the containers individually

docker-compose build docker-compose up -d mongo docker-compose up -d mysql docker-compose up -d node

check the running containers

docker ps

to stop the containers

docker-compose down

Sample commit messages

standard format

git commit -m "{{type}}: {{commit message}}"
type can be [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test]

for example:
git commit -m "fix: commit message"
git commit -m "improvement: commit message"

req.context payload sample

{
  user: {
    _id: 5e253a74b1f0752acd1154f1,
    firstName: 'Nirali',
    lastName: 'Mecwan',
    email: 'mecwannirali123@gmail.com',
    user_id: 5e253a74b1f0752acd1154f1,
    profilePictures: {
      orignal: '3587_8407_802482001606889323.jpeg',
      thumb: '3587_8407_802482001606889323.jpeg'
    },
    designation: 'Quality Assurance Engineer',
    organisation_name: 'Hubilo Virtual',
    isBlocked: false,
    user_id_sql: '66594'
  },
  event: {
    organiser_id: 66594,
    event_id: 3713,
    device_type: 'WEB',
    api_key: 'c891bd9a0f71b41556f515501a7d1c4e',
    start_time_milli: '1607664600000',
    end_time_milli: '1640975340000',
    name: 'React Version Upgrade Testing',
    is_deactive: 0,
    timezone_id: 94,
    description: '<p>&nbsp;</p>\n' +
      '<p>React Test&nbsp;</p>\n' +
      '<p>Google News is a news aggregator service developed by Google. It presents a continuous flow of articles organized from thousands of publishers and magazines. Google News is available as an app on Android, iOS, and the Web. Google released a beta version in September 2002 and the official app in January 2006 sample</p>\n' +
      '<p><a href="mailto:support@hubilo.com">support@hubilo.com</a></p>\n' +
      '<p>Tested by&nbsp;</p>\n' +
      '<p>Nirali<br />Jatin</p>',
    isPublished: 0
  },
  auth: true,
  community: {
    _id: 5fd2fafa4b75052c581ebec8,
    userId: 5e253a74b1f0752acd1154f1,
    isActive: 1,
    groups: [ 5fd2fafa4b75052c581ebec4, 5fd2fafa4b75052c581ebec6 ],
    guestAgendaIds: [],
    broadcastStudioAgendaIds: [ 20934 ],
    exhibitor_id: 431132,
    speaker_id: 123,
    host_id: 123
  }
}