API
TSCord is not only a Discord Bot, it has also an API in its core!
This API lets you interact with the bot instance and the DB from external services using REST requests.
It uses the routing-controllers
package under the hood, check the official documentation here to learn how to customize it and add new endpoints.
Initialization
First, you need to put a unique API_ADMIN_TOKEN in the .env
file (you can generate it here).
You can also customize the port it is running on.
API_PORT=4000
API_ADMIN_TOKEN="PUT_A_RANDOM_TOKEN_HERE"
Then, you'll have to enable the API server in the config as it is disabled by default:
export const generalConfig: GeneralConfigType = {
enabled: true,
port: process.env['API_PORT'] ? parseInt(process.env['API_PORT']) : 4000,
}
Swagger
The API includes an OpenAPI Swagger webpage, accessible at this endpoint:
/docs
It is an interactive documentation of all the endpoints and their parameters.
Authorization
Most of the API is protected by an authorization system. It is designed following a classic Bearer-like header authorization pattern.
It accepts two type of tokens:
- Discord OAuth2 token: the authorization system will fetch the actual discord user from the provided token, and then checks if its ID is included in the
devs
config property. - Admin Token: if the provided token correspond to the one in the
.env
, it will authorize the request.
Architecture
All the API code lives in src/api/
.
It is splitted as follow:
src/api/
├── controllers # all the controllers (= endpoints), grouped by module file
├── middlewares # the middlewares are functions that are executed before the controller
└── server.ts # the server itself