TODO: change api.conf URL references to use environment variables and add these variables to the docker-compose configuration for host domain
103 lines
2.6 KiB
JavaScript
103 lines
2.6 KiB
JavaScript
// set up a basic API for MySQL
|
|
// this is a simple API that will allow us to do basic CRUD operations on our MySQL database
|
|
|
|
// import the express module
|
|
const express = require('express');
|
|
const cors = require('cors')
|
|
|
|
// create an express app
|
|
const app = express();
|
|
|
|
// enable cors
|
|
var corsOptions = {
|
|
// origin: "http://localhost:5173"
|
|
};
|
|
// app.use(cors(corsOptions));
|
|
app.use(cors());
|
|
|
|
// parse requests of content-type - application/json
|
|
app.use(express.json());
|
|
|
|
// parse requests of content-type - application/x-www-form-urlencoded
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
// include all routes
|
|
const os = require('os');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const routesPath = path.join(__dirname, 'db/routes');
|
|
const routeFiles = fs.readdirSync(routesPath);
|
|
|
|
// auth providers
|
|
const bearerToken = require('express-bearer-token');
|
|
// const { expressjwt: jwt } = require("express-jwt");
|
|
|
|
for (const file of routeFiles) {
|
|
const { apiPath, apiRouter } = require(path.join(routesPath, file));
|
|
|
|
app.use(
|
|
apiPath,
|
|
// JWT Bearer token
|
|
// jwt({
|
|
// secret: process.env.JWT_SECRET,
|
|
// algorithms: ["HS256"],
|
|
// }),
|
|
// function (err, req, res, next) {
|
|
// if (err.name === "UnauthorizedError") {
|
|
// res.status(401).send("invalid token!");
|
|
// } else {
|
|
// next(err);
|
|
// }
|
|
// },
|
|
// simple plaintext Bearer token
|
|
bearerToken(),
|
|
function (req, res, next) {
|
|
if (req.token === process.env.BEARER_TOKEN) {
|
|
next();
|
|
} else {
|
|
res.status(401).send("invalid token!");
|
|
}
|
|
},
|
|
apiRouter
|
|
);
|
|
}
|
|
|
|
// sync/init database
|
|
const db = require('./db');
|
|
const dbConfig = require("./db/config.js");
|
|
// if database doesn't exist, create it
|
|
db.instance.query('CREATE DATABASE IF NOT EXISTS ' + dbConfig.DATABASE)
|
|
.then(() => {
|
|
console.log('Database created')
|
|
db.instance.sync({
|
|
force: true
|
|
});
|
|
})
|
|
.then(() => {
|
|
|
|
// configure api docs
|
|
const swaggerUi = require('swagger-ui-express');
|
|
const YAML = require('yamljs');
|
|
const swaggerDocument = YAML.load('openapi.yaml');
|
|
// local YAML
|
|
// app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
|
|
// explorer: true
|
|
// }));
|
|
|
|
// converted from Postman
|
|
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
|
|
explorer: true
|
|
}));
|
|
|
|
Promise.resolve()
|
|
}).then(() => {
|
|
|
|
// set port, listen for requests
|
|
app.listen(3000, function () {
|
|
console.log('App running on port ' + 3000);
|
|
});
|
|
|
|
}).catch((err) => {
|
|
console.log(err);
|
|
}); |