Start on API

This commit is contained in:
Isaac 2022-05-06 00:01:19 +01:00
parent a37d5e7613
commit 11ec090ab6
10 changed files with 52 additions and 3 deletions

View File

@ -124,7 +124,7 @@
"error" "error"
], ],
"multiline-comment-style": [ "multiline-comment-style": [
"warn" "off"
], ],
"no-console": [ "no-console": [
"off" "off"

View File

@ -1,4 +1,5 @@
CONFIG_PATH=./user/config.yml CONFIG_PATH=./user/config.yml
DISCORD_TOKEN= DISCORD_TOKEN=
DB_ENCRYPTION_KEY= DB_ENCRYPTION_KEY=
DB_CONNECTION_URL="" DB_CONNECTION_URL=""
HTTP_BIND=3000

View File

@ -35,9 +35,11 @@
"@prisma/client": "^3.13.0", "@prisma/client": "^3.13.0",
"discord.js": "^13.6.0", "discord.js": "^13.6.0",
"dotenv": "^16.0.0", "dotenv": "^16.0.0",
"fastify": "^3.29.0",
"figlet": "^1.5.2", "figlet": "^1.5.2",
"leeks.js": "^0.2.4", "leeks.js": "^0.2.4",
"leekslazylogger": "^4.1.7", "leekslazylogger": "^4.1.7",
"node-dir": "^0.1.17",
"semver": "^7.3.7", "semver": "^7.3.7",
"terminal-link": "^2.1.1", "terminal-link": "^2.1.1",
"yaml": "^1.10.2" "yaml": "^1.10.2"

37
src/http.js Normal file
View File

@ -0,0 +1,37 @@
const fastify = require('fastify')();
const { readFiles } = require('node-dir');
const { join } = require('path');
module.exports = client => {
const dir = join(__dirname, '/routes');
readFiles(dir,
{
exclude: /^\./,
match: /.js$/,
},
(err, content, next) => next(),
(err, files) => {
if (err) throw err;
for (const file of files) {
const path = file
.substring(0, file.length - 3) // remove `.js`
.substring(dir.length) // remove higher directories
.replace(/\[(\w+)\]/gi, ':$1') // convert [] to :
.replace('/index', '') || '/'; // remove index
const route = require(file);
Object.keys(route).forEach(method => fastify[method](path, {
config: { client },
...route[method],
})); // register route
}
fastify.listen(process.env.HTTP_BIND, (err, addr) => {
if (err) client.log.error.http(err);
else client.log.success.http(`Listening at ${addr}`);
});
},
);
};

View File

@ -30,6 +30,7 @@ const logger = require('./lib/logger');
const banner = require('./lib/banner'); const banner = require('./lib/banner');
const YAML = require('yaml'); const YAML = require('yaml');
const Client = require('./client'); const Client = require('./client');
const http = require('./http');
process.env.NODE_ENV ??= 'development'; // make sure NODE_ENV is set process.env.NODE_ENV ??= 'development'; // make sure NODE_ENV is set
require('dotenv').config(); // load env file require('dotenv').config(); // load env file
@ -74,4 +75,6 @@ process.on('unhandledRejection', error => {
const client = new Client(); const client = new Client();
client.config = config; client.config = config;
client.log = log; client.log = log;
client.login(); client.login().then(() => {
http(client);
});

View File

6
src/routes/index.js Normal file
View File

@ -0,0 +1,6 @@
module.exports.get = {
handler: (req, res) => {
const { client } = res.context.config;
return `Hello, I am ${client.user.username}!`;
},
};