Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

makeTemplateTag v2 #609

Open
pyramation opened this issue May 4, 2024 · 1 comment
Open

makeTemplateTag v2 #609

pyramation opened this issue May 4, 2024 · 1 comment

Comments

@pyramation
Copy link
Collaborator

export function makeTemplateTag(info: ProtoServiceMethodInfo, noLeadingSlash: boolean = true): t.TemplateLiteral {
    const route = info.url
        .split('/')
        .filter(a => a !== '')
        .map(a => {
            if (a.startsWith('{')) {
                // clean weird routes like this one:
                // /ibc/apps/transfer/v1/denom_traces/{hash=**}
                return a.replace(routeRegexForReplace, '')
            } else {
                return a;
            }
        })
        .join('/');
    const segments = route.split('/');
    const expressions: any = [];
    const quasis = [];
    let accumulatedPath = '';
    let isFirst = true;

    segments.forEach((segment, _index) => {
        if (noLeadingSlash && segment === '') return;

        if (segment.startsWith('{') && segment.endsWith('}')) {
            // Dynamic segment
            const paramName = segment.slice(1, -1);
            // Push the accumulated static text as a quasi before adding the expression
            quasis.push(t.templateElement({ raw: accumulatedPath + '/', cooked: accumulatedPath }, false));
            accumulatedPath = '';  // Reset accumulated path after adding to quasis

            // expressions.push(t.identifier(`params.${paramName}`));
            expressions.push(t.memberExpression(t.identifier('params'), t.identifier(info.casing?.[paramName] ? info.casing[paramName] : paramName)));
            // Prepare the next quasi to start with a slash if this is not the last segment
            isFirst = false;
        } else {
            // Accumulate static text, ensuring to prepend a slash if it's not the first segment
            accumulatedPath += (isFirst ? '' : '/') + segment;
            isFirst = false;
        }
    });

    // Add the final accumulated static text as the last quasi
    quasis.push(t.templateElement({ raw: accumulatedPath, cooked: accumulatedPath }, true));  // Mark the last quasi as tail

    return t.templateLiteral(quasis, expressions);
}
@pyramation
Copy link
Collaborator Author

closes with #610

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant