NodeJs Rest API using Clean Architecture, Typescript and Design Patterns
- To configure database server address, url expiry time, url prefix and port the server will listen on. It is necessary to create an .env file at the root of the project and define the following environment variables:
Example:
MONGO_URL=mongodb://localhost:27017/url-shortener
BASE_URL_PREFIX=http://localhost:3333
PORT=3333
URL_EXPIRES_AT_IN_HOURS=24
-
It is necessary to have at least version 16 of NodeJS, along with a package manager, such as Yarn or NPM, to proceed with the installation of the application;
-
To proceed with the installation, just use the commands:
-
Using Yarn
- yarn
- yarn build
- yarn start
-
Using NPM
- npm install
- npm run build
- npm run start
After executing the commands successfully, the following message will appear in the terminal:
Server running at <BASE_URL_PREFIX> (url configured in environment variables in BASE_URL_PREFIX)
- With the application started, it is possible to communicate with the API through two endpoints:
POST <BASE_URL_PREFIX>/shortenUrl
the <BASE_URL_PREFIX> is equivalent to the server url defined in the environment variables
{
"originalUrl" : string
}
The originalUrl
attribute contains the URL to be shortened.
{
"success" : boolean
"data": string
}
The success
attribute indicates the url was shortened successfully or not.
The data
attribute contains the shortened url.
GET <BASE_URL_PREFIX>/:urlId
the <BASE_URL_PREFIX> is equivalent to the server url defined in the environment variables
{
"urlId" : string
}
The urlId
attribute contains the URL shortened.
Redirects to original url or returns 404 indicating URL not found
API returns the following status codes:
Status Code | Description |
---|---|
200 | OK |
400 | BAD REQUEST |
404 | NOT FOUND |
500 | INTERNAL SERVER ERROR |
- Folder organization
- Domain: Application domain, contains the use case contracts and models;
- Data: Contains the implementation of the use cases and contracts for the dependencies of the use cases;
- Infra: Infrastructure, contains the implementation of contracts defined in the Data layer and other external dependencies;
- Main: Contains all files related to configuration, instantiation of all classes, definition of routes, middlewares, among others;
- Presentation: Contains definition of API and endpoints, handling of HTTP requests and related contracts;
- Validation: Contains the contracts and implementation of the validations used in the presentation layer, in the controllers.