Trouble Dynamically Loading JSON in Next.js via NPM Package

  Kiến thức lập trình

I have a TypeScript project that dynamically loads a json configuration file based on the value of an enum passed as a parameter to my getInstance function in my PlatformConfigurationFactory file.

  public static async getInstance(
    platform: Platform
  ): Promise<PlatformConfiguration> {
    const jsonData = await this.configurationRepository.getConfig(platform);
    if (!jsonData) {
      throw new Error("Configuration data not found");
    }

    this.jsonValidator.loadSchema();
    if (!this.jsonValidator.isValid(jsonData)) {
      throw new Error("Invalid JSON data according to schema");
    }

    return this.fromJson(jsonData);
  }

The JsonConfigurationRepository file is used to read the file and return its contents in Json.

import { IConfigurationRepository } from "../../application/interfaces/IJsonConfigurationRepository";
import { Platform } from "../../core/domain/Platform";
import fs from "fs/promises";
import path from "path";

export class JsonConfigurationRepository implements IConfigurationRepository {
  async getConfig(platform: Platform): Promise<any> {
    const fileName = `${platform}-config.json`;
    const filePath = path.resolve(__dirname, "../../data", fileName);

    try {
      const fileContent = await fs.readFile(filePath, "utf-8");
      return JSON.parse(fileContent);
    } catch (error) {
      console.error(`Error loading configuration for ${platform}:`, error);
      return null;
    }
  }
}

The files are stored in ./src/data directory and when TypeScript builds the files in the ./dist folder, the json files are present thanks to my configuration below.

{
  "compilerOptions": {
    "target": "ESNext",                          
    "experimentalDecorators": true,              
    "emitDecoratorMetadata": true,               
    "module": "ESNext",                          
    "rootDir": "./src",                          
    "moduleResolution": "Node",                  
    "baseUrl": "./",                             
    "paths": {                                   
      "@mylib/*": ["src/*"]
    },                                      
    "resolveJsonModule": true,                   
    "declaration": true,                         
    "declarationMap": true,                      
    "outDir": "./dist",                          
    "skipLibCheck": true                         
  },
  "include": [
    "src/**/*",
    "data/**/*.json",
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts",
    "**/*.test.ts"
  ]
}

The tests are ok, when I call my factory it returns the configuration of a platform that I pass as a parameter :

    const config = await PlatformConfigurationFactory.getInstance(
      Platform.Facebook
    );

This project is then stored in Gitlab’s Package Registry as an NPM package, which I install in a Next.js 14 project via npm i @mylib/platform-configurations.

But when I have an error when I call the same code in Next.js :

    const config = await PlatformConfigurationFactory.getInstance(
      Platform.Facebook
    );

Error:

Error loading configuration for facebook: [Error: ENOENT: no such file or directory, open ‘/Users/me/workspace/nextjs/.next/server/json/facebook-config.json’] {
errno: -2,
code: ‘ENOENT’,
syscall: ‘open’,
path: ‘/Users/me/workspace/nextjs/.next/server/json/facebook-config.json’
}
⨯ Error: Configuration data not found
at Generator.next ()
digest: “2762426514”
⨯ Error: Configuration data not found
at Generator.next ()
digest: “2762426514”

The code tries to load the file in the wrong path instead of loading the file in dist/data in the installed package. How can I fix the problem please?

LEAVE A COMMENT