0

I have simple application where I am using express server and TypeScript as a coding language. At first I can hit my endpoint successfully but when I change the model, I see the old data.

I have tried this approach as well but no luck, How to disable webpage caching in ExpressJS + NodeJS?.

What am I missing here?

  1. My index.ts (main) file
/**
 * Required External Modules
 */
import "reflect-metadata"
import * as dotenv from "dotenv";
import express from "express";
import cors from "cors";
import helmet from "helmet";
import routes from "./routes/routes";
import compress from 'compression';
const nocache = require('nocache');

dotenv.config();

/**
 * App Variables
 */
if (!process.env.PORT) {
    process.exit(1);
}

const PORT: number = parseInt(process.env.PORT as string, 10);

const app = express();

/**
 *  App Configuration
 */
app.use(helmet());
app.use(cors());
app.use(express.json());
app.disable('x-powered-by'); // Hide information
app.use(compress());
// app.disable('view cache');
// app.use((req, res, next) => {
//     res.set('Cache-Control', 'no-store')
//     next()
// })
app.use(nocache());
routes(app);

/**
 * Server Activation
 */
app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
});
  1. route declartions.
import { Application } from "express";
import asyncWrap from "../utils/asyncWrap";
import HealthController from "../controllers/health.controller";
import container from "../ioc.container";

export default function (application: Application) {
    const healthController = container.get<HealthController>(HealthController);
 
    application.get('/healthStatus', asyncWrap(healthController.healthCheck.bind(healthController)));
}
  1. asycWrap logic
    import { 
        Request as ExpressRequest, 
        Response as ExpressResponse, 
        NextFunction, 
    } from 'express';
    
    // Wraps async functions, catching all errors and sending them forward to express error handler
    export default function asyncWrap(controller: CallableFunction) {
        return async (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => {
            try {
               await controller(req, res, next);
            } catch (e) {
                next(e);
            }
        };
    }
  1. controller logic
import { inject, injectable } from "inversify";
import { HealthModel } from "../models/health.model";
import HealthService from "../services/health.service";
import { 
    Request as ExpressRequest, 
    Response as ExpressResponse, 
} from 'express';

@injectable()
export default class HealthController {

    constructor(
        @inject("HealthService") private HealthService: HealthService,
    ) { }

    public async healthCheck(req: ExpressRequest, res: ExpressResponse): Promise<HealthModel> {
        const returnThis = await this.HealthService.healthCheck();
        res.send(returnThis);
        return returnThis;
    }
}
  1. service logic
import { injectable } from "inversify";
import { HealthModel } from "../models/health.model";

@injectable()
export default class HealthService {

    public async healthCheck(): Promise<HealthModel> {
        const healthModel: HealthModel = {
            dateTime: new Date(),
            description: "Hello WOrld",
            status: "sdfadfad"
        }
        return healthModel;
    }
}
  1. Output (this is my old result)

enter image description here

GThree
  • 2,708
  • 7
  • 34
  • 67
  • nestjs caches class instance at server startup time. maybe this causes your problem. see https://docs.nestjs.com/fundamentals/injection-scopes – Bad Dobby Dec 20 '21 at 20:57
  • @BadDobby I am using `inversify` for DI. Am I missing something here when you mention nestJS? – GThree Dec 20 '21 at 21:00

1 Answers1

1

After spending almost a day, I found out that I was not compiling my .ts files after change (which is silly mistake from my end). So, it is obvious that compile won't pick up my newly added changes.

I added start script in package.json which will compile my .ts files + run the source file.

Here, is the package.json file:

  • AR
    "scripts": {
        "dev": "ts-node-dev --respawn --pretty --transpile-only src/index.ts",
        "compile": "tsc -p .",
        "test": "jest --coverage --color",
      }
  • ER
     "scripts": {
        "dev": "ts-node-dev --respawn --pretty --transpile-only src/index.ts",
        "compile": "tsc -p .",
        "test": "jest --coverage --color",
        "start": "npm run compile && npm run dev"
      }
GThree
  • 2,708
  • 7
  • 34
  • 67