Currently, I am working on developing a backend API using Express
with the support of @awaitjs/express
.
I'm encountering some challenges when it comes to dealing with 'double nested' endpoints.
For example:
// Within src/routes/routes.ts which serves as an api router file
// apiv1router is exported from this module
app.getAsync('/', (req, res, next) => {
res.send("I work");
})
-------
// Inside src/server.ts serving as the entry point
app.useAsync('/apiv1', apiv1router);
Accessing /apiv1
functions properly and produces the expected results.
However, when I attempt the following setup:
// src/routes/routes.ts
import { Router } from '@awaitjs/express';
import { router as accountsRouter } from './AccountRoutes/AccountRoutes';
const router = Router();
router.useAsync('/', accountsRouter);
------
// src/routes/AccountRoutes/AccountRoutes.ts
import { Request, Response, NextFunction } from 'express';
import { Router } from '@awaitjs/express';
router.getAsync(
'/accounts/:accountType',
async (request: Request, response: Response, next: NextFunction) => {
try {
requestValidator(request, next, response);
const accountsList = await accountModel.find({
accountType: request.params.accountType,
});
response.status(200).json(accountsList);
} catch (error) {
return error;
}
}
);
export { router as accountsRouter };
And then proceed to visit /apiv1/accounts/foobar
, it shows the message
<pre>Cannot GET /apiv1/accounts</pre>
leading to a 404 error [...] "GET /apiv1/accounts HTTP/1.1" 404 153
Any suggestions or insights on resolving this issue?
In addition to this, above my /apiv1
routing, I have:
import express, { Request, Response, Errback, NextFunction } from 'express';
import { addAsync } from '@awaitjs/express';
import helmet from 'helmet';
import cors from 'cors';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import mongoose from 'mongoose';
const PORT = process.env.PORT;
import { router as apiv1router } from './routes/routes';
const app = addAsync(express());
const mongoURI =
process.env.MONGOURI;
app.useAsync(express.json());
app.useAsync(helmet());
app.useAsync(cors());
app.useAsync(bodyParser.urlencoded({ extended: true }));
app.useAsync(morgan('common'));
// The error handling middleware for better management
app.useAsync((err: any, req: Request, res: Response, next: NextFunction) => {
console.error(err.stack);
});
Despite exploring alternate solutions before seeking help, none offered a satisfactory resolution so far.
UPDATE 1 Upon implementing:
router.getAsync(
'/accounts/:accountType',
async (request: Request, response: Response, next: NextFunction) => {
response.json(request.params.accountType)
}
);
The functionality works flawlessly. Could the culprit be related to mongoose
in this context?