72 lines
2.3 KiB
JavaScript
72 lines
2.3 KiB
JavaScript
require('dotenv').config();
|
|
|
|
const { setupFdk } = require('@gofynd/fdk-extension-javascript/express');
|
|
const { MemoryStorage } = require('@gofynd/fdk-extension-javascript/express/storage');
|
|
|
|
function normalizeEnvText(value) {
|
|
return typeof value === 'string' ? value.trim() : '';
|
|
}
|
|
|
|
function trimTrailingSlash(value) {
|
|
return normalizeEnvText(value).replace(/\/+$/, '');
|
|
}
|
|
|
|
function buildRedirectUrl(baseUrl, companyId) {
|
|
const normalizedBaseUrl = trimTrailingSlash(baseUrl);
|
|
const query = companyId ? `?blt-gtw-fc-cid=${encodeURIComponent(companyId)}` : '';
|
|
return `${normalizedBaseUrl}/${query}`.replace(/\/\?/, '/?');
|
|
}
|
|
|
|
function createFdkExtension() {
|
|
const apiKey = normalizeEnvText(process.env.EXTENSION_API_KEY);
|
|
const apiSecret = normalizeEnvText(process.env.EXTENSION_API_SECRET);
|
|
const baseUrl = normalizeEnvText(process.env.EXTENSION_BASE_URL || process.env.EXTENSION_URL);
|
|
const cluster = normalizeEnvText(process.env.EXTENSION_CLUSTER_URL) || 'https://api.fynd.com';
|
|
|
|
if (!apiKey || !apiSecret || !baseUrl) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
return setupFdk({
|
|
api_key: apiKey,
|
|
api_secret: apiSecret,
|
|
base_url: trimTrailingSlash(baseUrl),
|
|
cluster,
|
|
scopes: ['company/applications/read'],
|
|
callbacks: {
|
|
auth: async (req) => buildRedirectUrl(baseUrl, req?.fdkSession?.company_id || req?.query?.company_id || ''),
|
|
uninstall: async (req) => {
|
|
const companyId = req?.body?.company_id || req?.query?.company_id || req?.fdkSession?.company_id || '';
|
|
console.log(`[FDK] uninstall callback received for company ${companyId || 'unknown'}`);
|
|
},
|
|
},
|
|
storage: new MemoryStorage('sms_extension_'),
|
|
access_mode: 'offline',
|
|
});
|
|
} catch (error) {
|
|
console.warn(`[FDK] Failed to initialize FDK: ${error.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
const fdkExtension = createFdkExtension();
|
|
|
|
async function getPlatformClientForCompany(companyId) {
|
|
if (!fdkExtension) {
|
|
throw new Error('FDK is not configured');
|
|
}
|
|
|
|
if (!normalizeEnvText(companyId)) {
|
|
throw new Error('companyId is required to fetch a platform client');
|
|
}
|
|
|
|
return fdkExtension.getPlatformClient(companyId);
|
|
}
|
|
|
|
module.exports = {
|
|
fdkExtension,
|
|
isFdkConfigured: Boolean(fdkExtension),
|
|
getPlatformClientForCompany,
|
|
};
|