Skip to content

diasrodinei/as-challenge

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RESTful API Node Server to Search for Restaurants nearby

Build Status Coverage Status Codacy Badge PRs Welcome

A simple project to address a challenge.

By running a single command, you will get a production-ready Node.js app installed and fully configured on your machine. The app comes with many built-in features, such as request validation, unit and integration tests, continuous integration, docker support, API documentation, pagination, etc.

Its main function is to provide an api so that it is possible to search for nearby restaurants.

Manual Installation

Clone the repo:

git clone --depth 1 https://github.com/diasrodinei/as-challenge.git
cd as-challenge
npx rimraf ./.git

Install the dependencies:

yarn install

Set the environment variables:

cp .env.example .env

# open .env and modify the environment variables (if needed)

Features

  • Testing: unit and integration tests using Jest
  • Error handling: centralized error handling mechanism
  • API documentation: with swagger-jsdoc and swagger-ui-express
  • Process management: advanced production process management using PM2
  • Dependency management: with Yarn
  • Environment variables: using dotenv and cross-env
  • Security: set security HTTP headers using helmet
  • Santizing: sanitize request data against xss and query injection
  • CORS: Cross-Origin Resource-Sharing enabled using cors
  • Compression: gzip compression with compression
  • CI: continuous integration with Travis CI
  • Docker support
  • Code coverage: using coveralls
  • Code quality: with Codacy
  • Git hooks: with husky and lint-staged
  • Linting: with ESLint and Prettier
  • Editor config: consistent editor configuration using EditorConfig

Commands

Running locally:

yarn dev

Running in production:

yarn start

Testing

If you're running localhost, you can test it on http://localhost:3000/v1/docs from where you can use the Swegger to input the searching parameters and check the API answers.

You'll realise the Swegger do not let you to input a wrong data type. For example: If the field waits for a string, it doesn't let you inform a int. Therefore to test the funcionality that deal with those errors, you'll need to call for the GET directly via browser ou via Postman.

You can try http://localhost:3000/v1/restaurants?name=A&rate=1&distance=10&price=A&cuisine=American and you'll see that the validation will reject the type "string" for the parameter "price".

I hope you enjoy it!

Aditional Informations

Docker:

# run docker container in development mode
yarn docker:dev

# run docker container in production mode
yarn docker:prod

# run all tests in a docker container
yarn docker:test

Environment Variables

The environment variables can be found and modified in the .env file. They come with these default values:

# Port number
PORT=3000

## Project Structure

src
|--config\ # Environment variables and configuration related things |--controllers\ # Route controllers (controller layer) |--docs\ # Swagger files |--middlewares\ # Custom express middlewares |--routes\ # Routes |--services\ # Business logic (service layer) |--utils\ # Utility classes and functions |--validations\ # Request data validation schemas |--app.js # Express app |--index.js # App entry point


## API Documentation

To view the list of available APIs and their specifications, run the server and go to `http://localhost:3000/v1/docs` in your browser. This documentation page is automatically generated using the [swagger](https://swagger.io/) definitions written as comments in the route files.

### API Endpoints

List of available routes:

**Restaurants routes**:\
`GET /v1/restaurants` - get all users\

## Error Handling

The app has a centralized error handling mechanism.

Controllers should try to catch the errors and forward them to the error handling middleware (by calling `next(error)`). For convenience, you can also wrap the controller inside the catchAsync utility wrapper, which forwards the error.

```javascript
const catchAsync = require('../utils/catchAsync');

const controller = catchAsync(async (req, res) => {
  // this error will be forwarded to the error handling middleware
  throw new Error('Something wrong happened');
});

The error handling middleware sends an error response, which has the following format:

{
  "code": 404,
  "message": "Not found"
}

When running in development mode, the error response also contains the error stack.

The app has a utility ApiError class to which you can attach a response code and a message, and then throw it from anywhere (catchAsync will catch it).

For example, if you are trying to get a user from the DB who is not found, and you want to send a 404 error, the code should look something like:

const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const User = require('../models/User');

const getUser = async (userId) => {
  const user = await User.findById(userId);
  if (!user) {
    throw new ApiError(httpStatus.NOT_FOUND, 'User not found');
  }
};

Validation

Request data is validated using Joi. Check the documentation for more details on how to write Joi validation schemas.

The validation schemas are defined in the src/validations directory and are used in the routes by providing them as parameters to the validate middleware.

Logging

Import the logger from src/config/logger.js. It is using the Winston logging library.

Logging should be done according to the following severity levels (ascending order from most important to least important):

const logger = require('<path to src>/config/logger');

logger.error('message'); // level 0
logger.warn('message'); // level 1
logger.info('message'); // level 2
logger.http('message'); // level 3
logger.verbose('message'); // level 4
logger.debug('message'); // level 5

In development mode, log messages of all severity levels will be printed to the console.

In production mode, only info, warn, and error logs will be printed to the console.
It is up to the server (or process manager) to actually read them from the console and store them in log files.
This app uses pm2 in production mode, which is already configured to store the logs in log files.

Note: API request information (request url, response code, timestamp, etc.) are also automatically logged (using morgan).

About

AS Challenge

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages