[Question] How do I structure my application?

My controllers typically have like 1-4 things in them that are handled in different files.

Those have all the error handling, etc. and just return a { success: ____, message: ____} object.

The controller is basically the logic but not the implementation of that logic.

I could have it in a route (or resolver if using graphql) but I like to have routes just call the controller. Then I can change routes easily or add all in one place while controllers are separate. But they roughly align to routes.

Here's an express example....

My routes pretty much all look like:

router.use('checkout', async (req, res) => {

try {

const result = await checkoutController(req.body) ;

res.status(200).send(result);

} catch (e) {

res.status(500).send([success: false, message: e.message});

};

Then the controller might be something like:

async function checkoutController(payload) {

try {

// Validate throws error

await validate(payload);

// Payment throws error

const paymentResult = await makePayment(payload);

// Other stuff that doesnt throw error

const receiptResult = await sendReceipt(payload);

const dbResult = await dbTransaction(payload);

return { success: true, message: {paymentResult, receiptResult, dbResult });

} catch (e) {

return { success: false, message: e.message};

}

Hopefully that helps. After messing around for awhile I now have it so all routes are super simple and return the result of a controller (which really always should return something) or in some weird case a 500 error.

Controllers go step by step through usually 1-4 different calls to different functions that all return the same response ( a success and message) and the controller returns those.

Seems to work alright.

I'm fiddling around with nestjs and that organizes stuff for you. I like it

/r/node Thread Parent