cosmology-tech / telescope

A TypeScript Transpiler for Cosmos Protobufs ⚛️
https://cosmology.zone/products/telescope
Apache License 2.0
146 stars 43 forks source link

makeTemplateTag v2 #609

Open pyramation opened 5 months ago

pyramation commented 5 months ago
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 commented 5 months ago

closes with #610