This is my userHandler.js

const { data } = require('../../lib/data');
const { hash } = require('../../helpers/utilities');

// scaffolding
const handler = {};

handler.userHandler = (reqProps, callback) => {
    const acceptedMethods = ['GET', 'POST', 'PUT', 'DELETE'];
    if (acceptedMethods.indexOf(reqProps.method) > -1) {
        handler._users = {
            POST: (reqProps, callback) => {
                const firstName =
                    typeof reqProps.body.firstName === 'string' &&
                    reqProps.body.firstName.trim().length > 0
                        ? reqProps.body.firstName
                        : 'Type your name';

                const lastName =
                    typeof reqProps.body.lastName === 'string' &&
                    reqProps.body.lastName.trim().length > 0
                        ? reqProps.body.lastName
                        : 'Type your name';

                const phone =
                    typeof reqProps.body.phone === 'number' &&
                    reqProps.body.phone.toString().trim().length === 11
                        ? reqProps.body.phone
                        : 'Type your number';

                const password =
                    typeof reqProps.body.password === 'string' &&
                    reqProps.body.password.trim().length > 0
                        ? reqProps.body.password
                        : 'Type your password';

                const tosAgree =
                    typeof reqProps.body.tosAgree === 'boolean'
                        ? reqProps.body.tosAgree
                        : false;

                if (firstName && lastName && password && phone && tosAgree) {
                    data.read('users', phone, (err) => {
                        if (err) {
                            let userObject = {
                                firstName,
                                lastName,
                                phone,
                                password: hash(password),
                                tosAgree,
                            };
                            data.create('users', phone, userObject, (err) => {
                                if (!err) {
                                    console.log('User created successfully');
                                } else {
                                    console.log(
                                        err.message + "couldn't create user"
                                    );
                                }
                            });
                        } else {
                            callback(err.message + 'server side problem');
                        }
                    });
                } else {
                    callback('request problem');
                }
            },
        };
    } else {
        callback(405);
    }
};

module.exports = handler;

this is handleReqRes.js

const handler = {};
const url = require('url');
const { StringDecoder } = require('string_decoder');
const routes = require('../routes');
const { notFoundHandler } = require('../handlers/routeHandlers/notFoundHandler');
const { parseJSON } = require('./utilities');

handler.handleReqRes = (req, res) => {
    // request handle
    const parsedUrl = url.parse(req.url, true); // Passing true to parse query parameters
    const path = parsedUrl.pathname;
    const trimmedPath = path.replace(/^\/+|\/+$/g, '');
    const method = req.method.toUpperCase();
    const query = parsedUrl.query;
    const headers = req.headers; // Access headers from req.headers
    const reqProps = {
        parsedUrl,
        path,
        trimmedPath,
        method,
        query,
        headers,
    };

    const decoder = new StringDecoder('utf8');
    let contData = '';

    const chosenHandler = routes[trimmedPath] ? routes[trimmedPath] : notFoundHandler;

    req.on('data', (buffer) => {
        contData += decoder.write(buffer);
    });
    req.on('end', () => {
        contData += decoder.end(); // Correct usage of decoder.end()

        reqProps.body = parseJSON(contData);

        chosenHandler(reqProps, (status, payload) => {
            status = typeof status === 'number' ? status : 500;
            payload = typeof payload === 'object' ? payload : {};

            const payloadString = JSON.stringify(payload);
            console.log(status);

            // response
            res.setHeader('Content-type', 'application/json');
            res.writeHead(status, headers); // Include headers in writeHead
            res.end(payloadString);
        });
        // response handle
    });
};

module.exports = handler;

my routes are totally ok Below code is utilities.js

//dependencies
const utilities ={};
const crypto = require('crypto');
const environments = require('./environment');
//parse json to string
utilities.parseJSON = (jsonString)=>{ 
    let output;

    try{
        output = JSON.parse(jsonString);
    }
    catch{
        output={};
    };
    return output;
   
};
 utilities.hash = (str) =>{
        if(typeof str ==='string' && str.length>7){
            const hash = crypto.createHmac('sha256',environments.secretkey).update(str).digest('hex');
            return hash;
        }
            return false;
    }
//export module
module.exports = utilities;

I tried to solve the problem. I found that in handleReqRes.js the code is working till

  req.on('data', (buffer) => {
        contData += decoder.write(buffer);
    });

after this I am getting no response from chosenHandler. And I have no idea what is going on after that. So, it will be very helpful if I get knowledge what is going on the code and how can I get an error or response.

0

There are 0 answers