FIxed Index.js for api to handle form or json payload appropriately

master
raj 3 years ago
parent 7185b2d1c4
commit 294839b817

@ -1,12 +1,9 @@
const AdminJSFastify = require('@adminjs/fastify')
const AdminJS = require('adminjs')
const userController = require("./controllers/userController"); const userController = require("./controllers/userController");
const cors = require("cors"); const cors = require("cors");
const swagger = require("./config/swagger"); const swagger = require("./config/swagger");
const rawBody = require("raw-body"); const rawBody = require('raw-body')
const uuidv4 = require("uuid").v4; const uuidv4 = require("uuid").v4;
const fastify = require("fastify")({
const Fastify = require("fastify")({
logger: true, logger: true,
//disableRequestLogging: true, //disableRequestLogging: true,
genReqId(req) { genReqId(req) {
@ -15,6 +12,36 @@ const Fastify = require("fastify")({
}, },
}); });
// const Fastify = require("fastify");
// const Fastify = require("fastify");
// const server = Fastify({
// logger: true,
// // ajv: { plugins: [ajvPlugin] },
// genReqId(req) {
// // you get access to the req here if you need it - must be a synchronous function
// return uuidv4();
// },
// });
// fastify.register(View).ready((err) => {
// if (err) console.error(err);
// console.log(fastify.config.PORT); // or fastify[options.confKey]
// // output: { PORT: 3000 }
// engine: {
// ejs: require('ejs'),
// },
// root: join(__dirname, 'views/html'),
// });
const now = () => Date.now(); const now = () => Date.now();
const fastifyEnv = require("fastify-env"); const fastifyEnv = require("fastify-env");
@ -39,65 +66,83 @@ const options = {
schema: schema, schema: schema,
// data: data // optional, default: process.env // data: data // optional, default: process.env
}; };
Fastify.register(fastifyEnv, options).ready((err) => { fastify.register(fastifyEnv, options).ready((err) => {
if (err) console.error(err); if (err) console.error(err);
console.log(Fastify.config.PORT); // or fastify[options.confKey] console.log(fastify.config.PORT); // or fastify[options.confKey]
// output: { PORT: 3000 } // output: { PORT: 3000 }
Fastify.decorate("conf", { fastify.decorate("conf", {
port: Fastify.config.PORT, port: fastify.config.PORT,
APIVERSION: Fastify.config.APIVERSION, APIVERSION: fastify.config.APIVERSION,
}); });
}); });
const apiversion = "1.0.0"; const apiversion = "1.0.0";
const path = require("path"); const path = require("path");
// Using static content for swagger documentation. Generated swagger UI is not user friendly. // Using static content for swagger documentation. Generated swagger UI is not user friendly.
Fastify.register(require("fastify-static"), { fastify.register(require("fastify-static"), {
root: path.join(__dirname, "api-docs"), root: path.join(__dirname, "api-docs"),
prefix: "/api-docs", // optional: default '/' prefix: "/api-docs", // optional: default '/'
}); });
Fastify.register(require("fastify-swagger"), swagger.options);
fastify.register(require("fastify-swagger"), swagger.options);
const customJwtAuth = require("./customAuthJwt"); const customJwtAuth = require("./customAuthJwt");
Fastify.register(customJwtAuth); fastify.register(customJwtAuth);
//login route - accept user credentials and send a token with role . "user" role is required to use the app. //login route - accept user credentials and send a token with role . "user" role is required to use the app.
// support login using application/x-www-form-urlencoded so users can login via a web form in addition to api // support login using application/x-www-form-urlencoded so users can login via a web form in addition to api
Fastify.register(require("fastify-formbody")); fastify.register(require("fastify-formbody"));
// fastify.register(require('fastify-multipart'))
// fastify.register(require("fastify-cors"), {
// // put your options here
// origin: [
// new RegExp("http://localhost"),
// new RegExp("http://simply-backoffice.true2air.com"),
// new RegExp("http://localhost:3000"),
// ],
// credentials: true,
// optionsSuccessStatus: 200,
// });
Fastify.register((fastify, opts, done) => { fastify.register((fastify, opts, done) => {
Fastify.addContentTypeParser( fastify.addContentTypeParser(
"application/json", "application/json",
{ parseAs: "buffer" }, { parseAs: "buffer" },
function (_req, body, done) { function (_req, body, done) {
try { try {
done(null, body); done(null, body)
} catch (error) { } catch (error) {
error.statusCode = 400; error.statusCode = 400
done(error, undefined); done(error, undefined)
} }
} }
); )
done(null)
})
done(null);
});
Fastify.register(require("point-of-view"), {
fastify.register(require('point-of-view'), {
engine: { engine: {
nunjucks: require("nunjucks"), nunjucks: require('nunjucks')
}, },
root: path.join(__dirname, "views"), root: path.join(__dirname, "views"),
includeViewExtension: true, includeViewExtension: true,
}); });
// * This is for user login * // * This is for login user as a simply user *
Fastify.post("/api/login", { fastify.post("/api/login", {
schema: { schema: {
description: "This is for Login User", description: "This is for Login User",
tags: ["Login"], tags: ["Login"],
@ -124,7 +169,7 @@ Fastify.post("/api/login", {
); );
if (!phoneVerified) { if (!phoneVerified) {
reply.send({ reply.send({
armintatankdata: { simplydata: {
error: false, error: false,
phoneVerified: false, phoneVerified: false,
phone: loginObject.user.phone, phone: loginObject.user.phone,
@ -134,7 +179,7 @@ Fastify.post("/api/login", {
}); });
} else if (oneTimePasswordSetFlag) { } else if (oneTimePasswordSetFlag) {
reply.send({ reply.send({
armintatankdata: { simplydata: {
error: false, error: false,
phoneVerified: phoneVerified, phoneVerified: phoneVerified,
phone: loginObject.user.phone, phone: loginObject.user.phone,
@ -166,7 +211,7 @@ Fastify.post("/api/login", {
// console.log("sending token \n"); // console.log("sending token \n");
// console.log(token); // console.log(token);
reply.send({ reply.send({
armintatankdata: { simplydata: {
error: false, error: false,
apiversion: fastify.config.APIVERSION, apiversion: fastify.config.APIVERSION,
access_token: token, access_token: token,
@ -180,7 +225,7 @@ Fastify.post("/api/login", {
} }
} else { } else {
error = { error = {
armintatankdata: { simplydata: {
error: true, error: true,
code: 400, code: 400,
message: "Invalid UserId , Password supplied", message: "Invalid UserId , Password supplied",
@ -191,7 +236,7 @@ Fastify.post("/api/login", {
}, },
}); });
Fastify.get("/api/reset_token/:username", { fastify.get("/api/reset_token/:username", {
async handler(req, reply) { async handler(req, reply) {
try { try {
const get_user = await userController.getSingleUser(req); const get_user = await userController.getSingleUser(req);
@ -207,7 +252,7 @@ Fastify.get("/api/reset_token/:username", {
} catch (err) { } catch (err) {
console.log(err); console.log(err);
error = { error = {
armintatankdata: { simplydata: {
error: true, error: true,
code: 400, code: 400,
message: "Reset Token failed", message: "Reset Token failed",
@ -218,44 +263,48 @@ Fastify.get("/api/reset_token/:username", {
}, },
}); });
Fastify.get("/testtemp", (req, reply) => { fastify.get('/testtemp', (req, reply) => {
reply.view("layouts/main", {}); reply.view('layouts/main', {});
}); });
//fastify-auth plugin is required so we can define routes in seperate files and verify jwt supplied in preHandlers for each request. //fastify-auth plugin is required so we can define routes in seperate files and verify jwt supplied in preHandlers for each request.
const multer = require("fastify-multer"); const multer = require("fastify-multer");
Fastify.register(require("fastify-auth")); fastify.register(require("fastify-auth"));
const dbConnection = require("./config/config"); const dbConnection = require("./config/config");
Fastify.register(dbConnection); fastify.register(dbConnection);
Fastify.register(multer.contentParser); fastify.register(multer.contentParser);
const { Schema } = require("mongoose"); const { Schema } = require("mongoose");
// fastify.register(dbConnection); // fastify.register(dbConnection);
Fastify.register(require("./routes/usersRoute")); fastify.register(require("./routes/usersRoute"));
// Testing route allows for retrieving a user by phone so one can see what is the phone verification code sent for a given user's phone // Testing route allows for retrieving a user by phone so one can see what is the phone verification code sent for a given user's phone
// Also allows deletion of a user with a given phone number // Also allows deletion of a user with a given phone number
Fastify.register(require("./routes/forTestingRoute")); fastify.register(require("./routes/forTestingRoute"));
// fastify.get("/", (req, reply) => {
// reply.view("/templates/index.ejs", { text: "text" });
// });
// Run the server!
const start = async () => { const start = async () => {
const app = Fastify
const admin = new AdminJS({
databases: [],
rootPath: '/admin'
})
try { try {
// await AdminJSFastify.buildRouter(
// admin,
// app, await fastify.listen(3000, "0.0.0.0");
// ) fastify.log.info(`listening on ${fastify.server.address().port}`);
await app.listen(3000, "0.0.0.0"); fastify.log.info(`server listening on ${fastify.config}`);
Fastify.log.info(`listening on ${Fastify.server.address().port}`);
Fastify.log.info(`server listening on ${Fastify.config}`);
} catch (err) { } catch (err) {
Fastify.log.error(err); fastify.log.error(err);
process.exit(1); process.exit(1);
} }
}; };
start(); start();
Loading…
Cancel
Save