Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
5.3 kB
1
Indexable
Never
/* eslint-disable no-continue */
import { Context, HTTPStatus, ZodeError } from '@zode/zode';

import * as middlewares from '../../../middleware';
import * as commonHandlers from '../../../handlers';
import * as helpers from '../helpers';
import * as constants from './constants';
import * as types from './types';

export const getUrl = async (ctx: Context): Promise<any> => {
    middlewares.doClaimsVerification()(ctx);
    const reqBody = ctx.state?.body as types.getUrl_args;
    const downstream_data: types.downstream_resp = {};
    const cachingCalls = {};
    let error_count = 0;
    const urlResponse: types.getUrl_resp = {
        data: {
            url_details: [],
            response_status: constants.STATUS.FAILED,
        },
    };
    if (commonHandlers.isEmpty(reqBody)) {
        urlResponse.data.url_details.push({
            url_name: '',
            status: constants.STATUS.FAILED,
            error: 'URL data missing',
        });
        throw new ZodeError(
            commonHandlers.extendedHTTPStatus.BAD_REQUEST.toString(),
            commonHandlers.extendedHTTPStatus.BAD_REQUEST,
            'Invalid request',
            undefined,
            urlResponse.data.url_details as unknown as Error[]
        );
    }
    const requested_urls = Object.values(reqBody);
    for (const data of requested_urls) {
        const url_name = data.url_name as types.url_categories_type;
        const url_data = data.url_data;
        if (constants.url_list[url_name]) {
            const url_detail = constants.url_list[url_name];
            const { client_required_params, internal_required_params, internal_optional_params, all_params } =
                helpers.getAllParamsData(url_detail, ctx);
            // validation to check if client is sending all the required attributes or not
            if (client_required_params.length) {
                if (typeof url_data !== 'object') {
                    error_count++;
                    urlResponse.data.url_details.push({
                        url_name,
                        status: constants.STATUS.FAILED,
                        error: 'url_data must be an object',
                    });
                    continue;
                }
                const missing_params = client_required_params.reduce((prevVal: any, curVal) => {
                    prevVal.push(...commonHandlers.checkIfDataExists(ctx, url_data, curVal));
                    return prevVal;
                }, []);
                if (missing_params.length) {
                    error_count++;
                    urlResponse.data.url_details.push({
                        url_name,
                        status: constants.STATUS.FAILED,
                        error: `Missing required reqBody for ${url_name}: ${missing_params.join(', ')}`,
                    });
                    continue;
                }
            }
            // eslint-disable-next-line no-await-in-loop
            await helpers.downstreamCalls(url_name, downstream_data, ctx, url_data, cachingCalls);

            const params_list = helpers.generateParamsList(
                all_params,
                url_data,
                url_name,
                downstream_data,
                ctx,
                internal_required_params,
                internal_optional_params
            );

            // eslint-disable-next-line no-await-in-loop
            const url = await helpers.generateUrl(
                ctx,
                params_list,
                url_name,
                url_detail?.base_url as string,
                downstream_data,
                url_data
            );
            if (!commonHandlers.isEmpty(url)) {
                urlResponse.data.url_details.push({
                    url_name,
                    status: constants.STATUS.SUCCESS,
                    url,
                });
            } else {
                error_count++;
                urlResponse.data.url_details.push({
                    url_name,
                    status: constants.STATUS.FAILED,
                    error: `Failed to fetch url for ${url_name}`,
                });
            }
        } else {
            error_count++;
            urlResponse.data.url_details.push({
                url_name,
                status: constants.STATUS.FAILED,
                error: `Unsupported url_name :${url_name}`,
            });
        }
    }

    if (error_count === 0) {
        urlResponse.data.response_status = constants.STATUS.SUCCESS;
        return { ...urlResponse, status: HTTPStatus.OK };
    }
    if (error_count === requested_urls.length) {
        urlResponse.data.response_status = constants.STATUS.FAILED;
        throw new ZodeError(
            commonHandlers.extendedHTTPStatus.BAD_REQUEST.toString(),
            commonHandlers.extendedHTTPStatus.BAD_REQUEST,
            'Invalid request',
            undefined,
            urlResponse.data.url_details as unknown as Error[]
        );
    } else {
        urlResponse.data.response_status = constants.STATUS_PARTIAL.PARTIAL_SUCCESS;
        return { ...urlResponse, status: HTTPStatus.OK };
    }
};