简体   繁体   中英

Node js clean architecture cant return response

please I am trying to implement a clean architecture for my node.js rest API I studied a tutorial Using Clean Architecture for Microservice APIs in Node.js with MongoDB and Express ...the goal for me is to adapt the HTTP request and call my controller as a function and return a response

server.js

import express from 'express';
import dotenv from 'dotenv';
import bodyParser from 'body-parser';
import httpAdapter from './http_adapter';
import register from './register';

const app = express();
app.use(bodyParser.json());

dotenv.config();

app.post('/account/register', httpAdapter(register));

const port = 5000;
app.listen(port, () => console.log(`server running on port  ${port}`));

http_adpter.js

export default function httpAdapter(controller) {
    return (req, res) => {
        const httpRequest = {
            body: req.body,
            query: req.query,
            params: req.params,
            ip: req.ip,
            method: req.method,
            path: req.path,
            headers: {
                'Content-Type': req.get('Content-Type'),
                Referer: req.get('referer'),
                'User-Agent': req.get('User-Agent'),
            },
        };
        controller(httpRequest)
            .then((httpResponse) => {
                if (httpResponse.headers) {
                    res.set(httpResponse.headers);
                }
                res.type('json');
                res.status(httpResponse.statusCode).send(httpResponse.body);
            })
            .catch((e) =>
                res.status(500).send({ error: 'An unkown error occurred.' })
            );
    };
}

register.js

export default function register(httpRequest) {
    return () => {
        try {
            const user = httpRequest.body;
            console.log(user);
            return {
                headers: {
                    'Content-Type': 'application/json',
                },
                statusCode: 201,
                body: { user },
            };
        } catch (e) {
            // TODO: Error logging
            console.log(e);
            return {
                headers: {
                    'Content-Type': 'application/json',
                },
                statusCode: 400,
                body: {
                    error: e.message,
                },
            };
        }
    };
}

error

[nodemon] restarting due to changes...[nodemon] starting `babel-node ./src/server.js`
server running on port  5000
TypeError: controller(...).then is not a function
    at C:\Users\tukuyoma\Desktop\odemru\server\src\/http_adapter.js:17:5
    at Layer.handle [as handle_request] (C:\Users\tukuyoma\Desktop\odemru\server\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\tukuyoma\Desktop\odemru\server\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\tukuyoma\Desktop\odemru\server\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\tukuyoma\Desktop\odemru\server\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\tukuyoma\Desktop\odemru\server\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\tukuyoma\Desktop\odemru\server\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\tukuyoma\Desktop\odemru\server\node_modules\express\lib\router\index.js:275:10)
    at C:\Users\tukuyoma\Desktop\odemru\server\node_modules\body-parser\lib\read.js:130:5
    at invokeCallback (C:\Users\tukuyoma\Desktop\odemru\server\node_modules\raw-body\index.js:224:16)
[nodemon] restarting due to changes...
[nodemon] starting `babel-node ./src/server.js`


In http_adapter.js, Change

controller(httpRequest)
        .then((httpResponse) => {
            if (httpResponse.headers) {
                res.set(httpResponse.headers);
            }
            res.type('json');
            res.status(httpResponse.statusCode).send(httpResponse.body);
        })
        .catch((e) =>
            res.status(500).send({ error: 'An unkown error occurred.' })
        );

to

try{
    const httpResponse =  controller(httpRequest);
    if (httpResponse.headers) {
       res.set(httpResponse.headers);
    }
    res.type('json');
    res.status(httpResponse.statusCode).send(httpResponse.body);
} 
catch (err) {
    res.status(500).send({ error: 'An unkown error occurred.' });
}

Should Work if every thing else is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM