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 cors = require("cors");
const swagger = require("./config/swagger");
const rawBody = require("raw-body");
const rawBody = require('raw-body')
const uuidv4 = require("uuid").v4;
const Fastify = require("fastify")({
const fastify = require("fastify")({
logger: true,
//disableRequestLogging: true,
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 fastifyEnv = require("fastify-env");
@ -39,65 +66,83 @@ const options = {
schema: schema,
// data: data // optional, default: process.env
};
Fastify.register(fastifyEnv, options).ready((err) => {
fastify.register(fastifyEnv, options).ready((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 }
Fastify.decorate("conf", {
port: Fastify.config.PORT,
APIVERSION: Fastify.config.APIVERSION,
fastify.decorate("conf", {
port: fastify.config.PORT,
APIVERSION: fastify.config.APIVERSION,
});
});
const apiversion = "1.0.0";
const path = require("path");
// 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"),
prefix: "/api-docs", // optional: default '/'
});
Fastify.register(require("fastify-swagger"), swagger.options);
fastify.register(require("fastify-swagger"), swagger.options);
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.
// 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.addContentTypeParser(
fastify.register((fastify, opts, done) => {
fastify.addContentTypeParser(
"application/json",
{ parseAs: "buffer" },
function (_req, body, done) {
try {
done(null, body);
done(null, body)
} catch (error) {
error.statusCode = 400;
done(error, undefined);
error.statusCode = 400
done(error, undefined)
}
}
);
)
done(null)
})
done(null);
});
Fastify.register(require("point-of-view"), {
fastify.register(require('point-of-view'), {
engine: {
nunjucks: require("nunjucks"),
nunjucks: require('nunjucks')
},
root: path.join(__dirname, "views"),
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: {
description: "This is for Login User",
tags: ["Login"],
@ -124,7 +169,7 @@ Fastify.post("/api/login", {
);
if (!phoneVerified) {
reply.send({
armintatankdata: {
simplydata: {
error: false,
phoneVerified: false,
phone: loginObject.user.phone,
@ -134,7 +179,7 @@ Fastify.post("/api/login", {
});
} else if (oneTimePasswordSetFlag) {
reply.send({
armintatankdata: {
simplydata: {
error: false,
phoneVerified: phoneVerified,
phone: loginObject.user.phone,
@ -166,7 +211,7 @@ Fastify.post("/api/login", {
// console.log("sending token \n");
// console.log(token);
reply.send({
armintatankdata: {
simplydata: {
error: false,
apiversion: fastify.config.APIVERSION,
access_token: token,
@ -180,7 +225,7 @@ Fastify.post("/api/login", {
}
} else {
error = {
armintatankdata: {
simplydata: {
error: true,
code: 400,
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) {
try {
const get_user = await userController.getSingleUser(req);
@ -207,7 +252,7 @@ Fastify.get("/api/reset_token/:username", {
} catch (err) {
console.log(err);
error = {
armintatankdata: {
simplydata: {
error: true,
code: 400,
message: "Reset Token failed",
@ -218,43 +263,47 @@ Fastify.get("/api/reset_token/:username", {
},
});
Fastify.get("/testtemp", (req, reply) => {
reply.view("layouts/main", {});
fastify.get('/testtemp', (req, reply) => {
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.
const multer = require("fastify-multer");
Fastify.register(require("fastify-auth"));
fastify.register(require("fastify-auth"));
const dbConnection = require("./config/config");
Fastify.register(dbConnection);
Fastify.register(multer.contentParser);
fastify.register(dbConnection);
fastify.register(multer.contentParser);
const { Schema } = require("mongoose");
// 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
// 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 app = Fastify
const admin = new AdminJS({
databases: [],
rootPath: '/admin'
})
try {
// await AdminJSFastify.buildRouter(
// admin,
// app,
// )
await app.listen(3000, "0.0.0.0");
Fastify.log.info(`listening on ${Fastify.server.address().port}`);
Fastify.log.info(`server listening on ${Fastify.config}`);
await fastify.listen(3000, "0.0.0.0");
fastify.log.info(`listening on ${fastify.server.address().port}`);
fastify.log.info(`server listening on ${fastify.config}`);
} catch (err) {
Fastify.log.error(err);
fastify.log.error(err);
process.exit(1);
}
};

Loading…
Cancel
Save