# JavaScript

<details>

<summary>Without Router - Current Approach</summary>

```javascript
// Assuming this as previous logic without Router
const axios = require('axios');

const entityMetadataFromCR = {
    baseUrl: 'http://fip-1.dev.sahamati.org.in/fip-simulate',
    id: "FIP-SIMULATOR"
}

const getHttpConfig = ({ baseUrl, route, headers, data, methodType }) => {
    return { url: `${baseUrl}${route}`, headers: headers, data, methodType };
};

const executeDiscoveryRequest = () => {
    const route = '/v2/Accounts/discover';

    const config = getHttpConfig({ baseUrl: entityMetadataFromCR.baseUrl, route, headers: {}, data: {}, methodType: 'POST' });

    axios.request(config)
        .then(response => response.data)
        .catch(error => {
            console.error('Error making discovery request:', error.message);
            throw error;
        });

};

const performAnotherOperations = async (accountDiscoverResponse) => {
    console.log('Perform another operations with the response', accountDiscoverResponse);
}

executeDiscoveryRequest()
    .then(performAnotherOperations)
    .then(() => console.log('Account discovery successful.'))
    .catch(() => console.log('Account discovery failed.'))
    .finally(() => console.log('Account discovery completed.'));

```

</details>

<details>

<summary>With Router Integration - Request</summary>

```javascript
const axios = require('axios');

// Entity metadata (from CR)
const entityMetadataFromCR = {
    baseUrl: 'http://fip-1.sandbox.sahamati.org.in/fip-simulate',
    id: 'FIP-SIMULATOR'
};

// Router Integration Helper URL
const ROUTER_INTEGRATION_HELPER_URL = 'https://api.sandbox.sahamati.org.in/router-helper/v1/request/header';

/**
 * Builds a base axios config
 */
const getHttpConfig = ({ baseUrl, route, headers = {}, data = {}, methodType = 'POST' }) => {
    return {
        url: `${baseUrl}${route}`,
        method: methodType,
        headers: {
            'Content-Type': 'application/json',
            ...headers
        },
        data
    };
};

/**
 * Calls Router Integration Helper Service to get host + x-request-meta
 */
const routerIntegrationHelper = async (route, rebitRequestBody) => {
    const payload = {
        rebitAPIEndpoint: route,
        recipientId: entityMetadataFromCR.id,
        customerId: '9875438980@AA_SIMULATOR',
        requestBody: rebitRequestBody
    };

    const response = await axios.post(ROUTER_INTEGRATION_HELPER_URL, payload, {
        headers: { 'Content-Type': 'application/json' }
    });

    return response.data; // { host, x-request-meta }
};

/**
 * Adds Sahamati Router headers + updates URL
 */
const addSahamatiConfiguration = async ({ config, route, rebitRequestBody }) => {
    const headerResponse = await routerIntegrationHelper(route, rebitRequestBody);

    const host = headerResponse.host;
    const xRequestMeta = headerResponse['x-request-meta'];

    config.url = `${host}${route}`;
    config.headers['x-request-meta'] = xRequestMeta;

    return config;
};

/**
 * Executes account discovery
 */
const executeDiscoveryRequest = async () => {
    const route = '/Accounts/discover';
    const rebitRequestBody = {}; // ReBIT defined request body

    let config = getHttpConfig({
        baseUrl: entityMetadataFromCR.baseUrl,
        route,
        headers: {},
        data: rebitRequestBody,
        methodType: 'POST'
    });

    // Add Sahamati configuration
    config = await addSahamatiConfiguration({ config, route, rebitRequestBody });

    const response = await axios.request(config);
    return response.data;
};

/**
 * Example: further operations after discovery
 */
const performAnotherOperations = async (accountDiscoverResponse) => {
    console.log('Next steps with response:', accountDiscoverResponse);
};

// Run discovery flow
(async () => {
    try {
        const response = await executeDiscoveryRequest();
        console.log('Account discovery successful:', response);

        await performAnotherOperations(response);
    } catch (error) {
        console.error('Account discovery failed. Error:', error.message);
    } finally {
        console.log('Account discovery completed.');
    }
})();

```

</details>

<details>

<summary>With Router Integration - Response</summary>

```javascript
const express = require('express');
const axios = require('axios');

const app = express();
app.use(express.json());

const ROUTER_RESPONSE_HEADER_URL = 'https://api.sandbox.sahamati.org.in/router-helper/v1/response/header';
const RECIPIENT_ID = 'AA-SIMULATOR';

function fetchAccountFromRequestBody(requestBody) {
    if (!requestBody) return null;
    const customer = requestBody.Customer;
    if (!customer || typeof customer !== 'object') return null;
    const identifiers = customer.Identifiers;
    if (!Array.isArray(identifiers)) return null;
    for (const idObj of identifiers) {
        if (typeof idObj !== 'object') continue;
        const { category, type, value } = idObj;
        if (category === 'STRONG' && type === 'AADHAAR' && value) {
            return {
                FIType: 'DEPOSIT',
                accType: 'SAVINGS',
                accRefNumber: 'BANK11111111',
                maskedAccNumber: 'XXXXXXX3468',
            };
        }
    }
    return null;
}

async function routerIntegrationHelper(requestBody) {
    const resp = await axios.post(ROUTER_RESPONSE_HEADER_URL, requestBody, {
        headers: { 'Content-Type': 'application/json' },
        timeout: 30000,
    });
    return resp.data;
}

app.post('/accounts/discover', async (req, res) => {
    const incomingRequestBody = req.body;
    const discoveredAccount = fetchAccountFromRequestBody(incomingRequestBody);
    if (!discoveredAccount) {
        return res.status(404).json({ error: 'Account not found' });
    }
    const responseBody = {
        ver: '2.0.0',
        timestamp: new Date().toISOString(), // Use current timestamp
        txnid: 'f35761ac-4a18-11e8-96ff-0277a9fbfedcs',
        DiscoveredAccounts: [discoveredAccount],
    };
    const responseHeaderRequestBody = {
        rebitAPIEndpoint: '/accounts/discover',
        customerId: '9977336577@aa_simulator', // Optionally extract from incomingRequestBody
        recipientId: RECIPIENT_ID,
        additionalAttributes: {},
        responseBody,
    };
    try {
        const responseHeaderResp = await routerIntegrationHelper(responseHeaderRequestBody);
        const xResponseMeta = responseHeaderResp['x-response-meta'];
        if (xResponseMeta) {
            res.set('x-response-meta', xResponseMeta);
        }
    } catch (err) {
        // Optionally log error or handle as needed
    }
    res.json(responseBody);
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});


```

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developer.sahamati.org.in/sahamatinet-mvp/integration-steps/integration-with-router/sample-code-snippets/javascript.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
