0

I'm trying to centralize endpoints to a single JSON file in my api folder.

{ 
  EndPoint: {
     Action: {
        path1: '/thisispath1/{id}',
        path2: '/thisispath2/',
     }
}

What I want to do is get the path name kinda of like how useTranslations works.

    const t = useTranslations('Endpoint');
    const path = t('Acton.path1',1);
//path = '/thisispath1/1';

Not sure where to start with this.

It some what worked with the top level node. i.e. GetEndpoint('EndPoint'); returns

     Action: {
        path1: '/thisispath1/{id}',
        path2: '/thisispath2/',
     }

but not GetEndpoint('EndPoint.Action.path1',1); returns undefined


type EndPointKeys = keyof typeof endPoints;

export const GetEndPoint = (action: string, parameter: string) => {

//Think I have to a recursive keyof typeof here?

    return endPoints[action as keyof typeof endPoints];

};

What I ended doing:


import endPoints from '../service-end-points/service-constants.json';

const jsonPathToValue = (Points: any, path: string) => {

    let jsonData = Points;
    let newpath = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    newpath = newpath.replace(/^\./, ''); // strip a leading dot
    const pathArray = newpath.split('.');
    let key = '';
    for (let i = 0; i <= pathArray.length; i++) {
        key = pathArray[i];
        if (key in jsonData) {
            if (jsonData[key as keyof typeof jsonData] !== null) {
                jsonData = jsonData[key as keyof typeof endPoints];
            }
        }
    }
    const finalPath = pathArray.slice(-1)[0];
    try {
        if (jsonData?.Actions[finalPath]) {
            return jsonData?.Actions[finalPath];
        }
    } catch (e) {
        return null;
    }
};

export const GetEndPoint = (path: string) => {
    const url = jsonPathToValue(endPoints, path);
    const HOST = process.env.CONSTELLATION_SERVICE_URL || null;
    if (!HOST) {
        throw new Error('SERVICE HOST NOT DEFINED');
    }
    return `${HOST}${url}`;
};

1 Answers1

1

In fact, what you want is convert a string t a JSON path. You can check this post it should answer your question.

You will have some different solutions to solve that.

Porzio Jonathan
  • 536
  • 2
  • 13
  • Thanks - link seems broken. Found [link](https://stackoverflow.com/questions/27628573/how-to-convert-a-string-to-jsonpath) is that it? – itsjustcarlos May 24 '23 at 00:21
  • Just repaired the link, yes exactly, here you have some solutions for your problem – Porzio Jonathan May 24 '23 at 00:35
  • Got it working! Had to do an extra step of: ```if (jsonData?.Actions[finalPath]) { return jsonData?.Actions[finalPath]; }``` and add some types for typescript. Thanks again for your help. – itsjustcarlos May 24 '23 at 19:48
  • yes you had to check if variable are null or not you can put answer as accepted if this solution fit for you. – Porzio Jonathan May 25 '23 at 00:26