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

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 YAML = require('yaml');
const Client = require('./client');
const http = require('./http');
process.env.NODE_ENV ??= 'development'; // make sure NODE_ENV is set
require('dotenv').config(); // load env file
@@ -74,4 +75,6 @@ process.on('unhandledRejection', error => {
const client = new Client();
client.config = config;
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}!`;
},
};