A delightful way building a Node.js RESTful API written in TypeScript.
Inspired by the awesome AWS Lambda Boilerplate of my former techlead.
Crafted with ❤️ by jL.
npx jl-tsnode-express
git clone https://github.com/johnliveeoroncillo/tsnode-rest-boilerplate.git
Requires Node.js v10+, Typescript and Docker (optional) to run.
Install the dependencies and devDependencies and start the server.
Link to docker: Docker
npm i -g node
npm i -g typescript
npm i -g ts-node
npm run dev
npm run build
npm run start
- Download this VSCode Extension Name: PlantUML Id: jebbs.plantuml Description: Rich PlantUML support for Visual Studio Code. Version: 2.17.2 Publisher: jebbs VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=jebbs.plantuml
- Download JRE for PlantUML Preview in VSCode - https://java.com/en/download/
- Open your .puml file in vscode
- Press ALT + D
- Open your .puml file in vscode
- Press CTRL + SHIFT + P
- Select PlantUML: Export Current Diagram
- Select your desired file extension
- Integrated Redis, MySql and Postgres using Typeorm
- Auto creation of API Routes.
- Support Middleware for Authorization
- Test API using Jest
- Parallel Processing or Events
- Create sequence diagram using PlantUML
- Create api documentation using apidoc
- and many more ..
https://github.com/johnliveeoroncillo/tsnode-rest-boilerplate/projects/
tsnode-rest-boilerplate
└─code_templates (Templates)
└─core (Main Core of the boilerplate)
└─docs (API Documentations)
└─migrations (Migration files)
└─seeder (Seed fake data to table)
└─src
| └─functions
| | └─apis (Contains API Routes)
| | | └─sample-api (Created from npm run make:api sample-api)
| | | | config.yml (API Configuration)
| | | | handler.ts (1st lifecycle of the API)
| | | | action.ts (Action of the API connected to handler)
| | | | request.ts (Allowed Body Request)
| | | | response.ts (List of responses of the API)
| | | | validate.ts (Body Request Validation)
| | | | handler_test.ts (Unit Testing)
| | └─cron (Contains Cron Jobs)
| | | └─sample-cron (Created from npm run make:cron sample-cron)
| | | | config.yml (Cron Configuration)
| | | | handler.ts (1st lifecycle of the CRON)
| | └─events (Contains Events)
| | | └─event_test (Created from npm run make:event event_test)
| | | | config.yml (Event Configuration)
| | | | handler.ts (1st lifecycle of the event)
| | | | action.ts (Action of the event connected to handler)
| | | | request.ts (Allowed Body Payload)
| | | | response.ts (List of responses of the event)
| | | | validate.ts (Payload Validation)
| | | | handler_test.ts (Unit Testing)
| | └─middlewares (Middlware of the API)
| | | | authorizer.ts (Sample middleware for authentication)
| | └─services (Custom Services)
| └─helpers (Helpers folder)
| └─models (Table Models)
| └─repository (Table Repository)
| .env.example
| artisan.ts
| .eslintrc.js
| .gitignore
| .prettierrc
| docker-compose.yml (Docker image files and database configurations)
| jest.config.js
| migrate.ts
| tsconfig.json
sample-api: (API Key)
handler: ./src/functions/apis/sample-api/handler (1st lifecycle of the API)
endpoint: /sample-api (API Route)
method: post (API Method)
enabled: true (Enable/Disable option)
middleware: authorizer (File name of the middleware)
version: 1 (Optional: Version of the api)
prefix: api (Optional: API prefix)
Enabled Version: /v1/sample-api
Enabled Prefix: /api/sample-api
Enabled Prefix and Version: /api/v1/sample-api
With path parameters: /sample-api/{id}
cron_today: (Cron Key)
handler: ./src/functions/cron/cron_today/handler (1st lifecycle of the CRON)
enabled: false (Enable/Disable option)
cron: '* * * * * *' (Cron frequency)
timezone: 'Asia/Manila' (Timezone)
event_test: (Event Key)
handler: ./src/functions/events/event_test/handler (1st lifecycle of the API)
enabled: true (Enable/Disable option)
#DATABASE CONFIGURATION
##MYSQL
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USERNAME=root
MYSQL_PASSWORD=admin
MYSQL_DB=database
##POSTGRES
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USERNAME=root
POSTGRES_PASSWORD=admin
POSTGRES_DB=database
##OTHER DB OPTIONS
DB_LOGGING=true
##REDIS
REDIS_HOST=127.0.0.1
REDIS_USERNAME=root
REDIS_PASSWORD=admin
REDIS_PORT=6379
REDIS_TTL=3600
#JWT CONFIGURATION
JWT_TOKEN=
JWT_ADMIN_TOKEN=
#CRYPTO SECRET KEY
SECRET_KEY=abcdef0123456789abcdef0123456789
#ALLOWED ORIGINS (CORS) - currently unavailable or not working
ALLOWED_ORIGINS=
#EVENT
EVENT_HOST=127.0.0.1
This is only a sample api to explore the boilerplate. You can also create your own API based on your requirements.
https://tsnode-rest-dev.herokuapp.com/
https://tsnode-rest-prod.herokuapp.com/
Endpoint: /redis/insert
Method: POST
Request:
{
key: 'my-key',
value: ['value1', 'value2']
}
Endpoint: /redis/:key
Method: GET
Endpoint: /login
Method: POST
Request:
{
username: '',
password: ''
}
Endpoint: /profile
Authorization: Bearer <TOKEN FROM LOGIN>
Method: GET
Endpoint: /login/admin
Method: POST
Request:
{
username: '',
password: ''
}
Endpoint: /profile/admin
Authorization: Bearer <TOKEN FROM LOGIN>
Method: GET
Endpoint: /register
Method: POST
Request:
{
username: '',
password: '',
scope: '' <- ADMIN or CLIENT
}
npm run make:model <model_name> <table_name>
npm run make:repository <repository_name> <table_name>
This will create model and repository
npm run make:migration <table_name>
npm run make:api <api_path>
Example:
npm run make:api admin/login
npm run make:api admin/management/users
npm run make:service <service_name>
npm run make:cron <cron_name>
npm run make:socket <socket_event_name>
Sample: ./src/functions/socket/socket_test
## Server Side Usage: ##
### NOTE: NO NEED FOR "on" LISTENER ON SERVER SIDE! e.g. io.socket.on('socket_test', (payload) => ....)
### THE FOLDER ITSELF ALREADY LISTENED/INITIALIZED TO SOCKET EVENTS
/** SEND TO SELF */
io.socket.emit('socket_test', payload);
/** BROADCAST TO ALL INCLUDING SENDER */
io.socketio.broadcastAll('socket_test', payload);
/** BROADCAST TO ALL EXCLUDING SENDER */
io.socket.broadcast.emit('socket_test', payload);
## GLOBAL USAGE ##
app.get('socketio').broadcastAll('my_event', payload);
### SEND TO SPECIFIC ID
app.get('socketio').sendToId(socket_id, 'my_event', payload);
## Client Side Usage: ##
socket.emit('socket_test', payload);
socket.on('socket_test', (payload) => ...)
Ref: https://socket.io
npm run make:event <event_name>
This function is inspired by AWS Lambda Event which drives the invocation or Lambda polls a queue or data stream and invokes the function in response to activity in the queue or data stream.
This custom event is using "worker_threads" module to recreate the AWS Lambda Event functionality. Wherein it executes functions in parallel process and doesn't affect the current thread of your API.
import { EVENTS } from "../../helpers/Enums";
import { invokeEvent, invokeEventWithResponse } from "../../core/libs/Events";
//OPTION 1 - Event with Response
const data = await invokeEventWithResponse(EVENTS.EVENT_TEST, { message: request.message });
return data;
//OPTION 2 - Event without Response
await invokeEvent(EVENTS.EVENT_TEST, { message: request.message });
npm run make:doc <name>
npm run build:doc
Optional: Edit apidoc.json
npm run lint
npm run migrate
npm run migrate:refresh
npm run cron
npm run dev:event
To run tests, run the following command
npm run test <path_file>
Example: npm run test ./apis/login/
npm run test:log <path_file>
Example: npm run test:log ./apis/login/
npm run docker:start
npm run docker:stop
Want to contribute? Great! Email me at [email protected]
GNU GPLv3