UNPKG

eregistrations-js

Version:

A JavaScript library that simplifies usage of eRegistrations APIs.

212 lines (211 loc) 8.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createOrModifyDatabase = createOrModifyDatabase; exports.getDatabaseSchema = getDatabaseSchema; exports.getList = getList; /** * Creates or modifies a database in GDB * @param config Configuration object with API, auth details, and database properties * @returns A promise resolving to the created or modified database */ async function createOrModifyDatabase(config) { try { if (!config || !config.baseApiUrl) { throw new Error('Invalid configuration: baseApiUrl is required'); } if (!config.token) { throw new Error('Invalid configuration: token is required'); } if (!config.catalogName) { throw new Error('catalogName is required'); } if (!config.code) { throw new Error('code is required'); } if (config.version === undefined) { throw new Error('version is required'); } console.log(`Creating or modifying database: ${config.catalogName}`); const url = `${config.baseApiUrl}/api/v1/database/modify`; // Prepare the database data from the config const databaseData = { catalog_name: config.catalogName, name: config.catalogName, code: config.code, version: config.version, numberFormat: config.numberFormat || '{code}{indexNoByCode}', indexNoByCode: config.indexNoByCode || '0', indexNo: config.indexNo || '0', schemaTags: config.schemaTags || [], schemaFlags: config.schemaFlags || [], schema: config.schema || { type: 'object', properties: { ID: { type: 'string', triggers: [ { conditions: [ { logic: '==', value: '', gate: '&&' } ], actions: [ { type: 'set-value', value: '{code}{indexNoByCode}', field_id: 1 }, { type: 'upper-case', field_id: 1 } ] } ], primaryKey: true, readOnly: true, $id: 1 } }, required: ['ID'], $incrementIndex: 1 }, isDraft: config.isDraft !== undefined ? config.isDraft : true, logo: config.logo !== undefined ? config.logo : null, fields_uniques: config.fields_uniques || [[]], order_fields: config.order_fields || [], indexes: config.indexes || {}, group_name: config.group_name !== undefined ? config.group_name : null }; const response = await fetch(url, { method: 'POST', headers: { 'Authorization': `Bearer ${config.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(databaseData) }); if (!response.ok) { if (response.status === 401) { throw new Error('Authentication failed: Invalid or expired token'); } throw new Error(`Failed to create or modify database: ${response.statusText}`); } const data = await response.json(); console.log(`Successfully created or modified database: ${config.catalogName}`); // Add the link to the database in the response const link = `${config.baseApiUrl}/#/app/database/${data.id}/modify`; return { ...data, link }; } catch (error) { console.error('Error creating or modifying database:', error); throw error; } } /** * Gets database schema information from GDB * @param config Configuration object with API, auth details, and databaseId * @returns A promise resolving to the database schema */ async function getDatabaseSchema(config) { try { if (!config || !config.baseApiUrl) { throw new Error('Invalid configuration: baseApiUrl is required'); } if (!config.token) { throw new Error('Invalid configuration: token is required'); } if (!config.databaseId) { throw new Error('databaseId is required'); } console.log(`Fetching database schema for database ID: ${config.databaseId}`); const url = `${config.baseApiUrl}/database/${config.databaseId}`; const response = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${config.token}`, 'Content-Type': 'application/json' } }); if (!response.ok) { if (response.status === 401) { throw new Error('Authentication failed: Invalid or expired token'); } else if (response.status === 404) { throw new Error(`Database with ID ${config.databaseId} not found`); } throw new Error(`Failed to fetch database schema: ${response.statusText}`); } const data = await response.json(); console.log(`Successfully fetched schema for database ID: ${config.databaseId}`); return data; } catch (error) { console.error('Error fetching database schema:', error); throw error; } } /** * Queries data from a GDB database * @param config Configuration object with API, auth details, code, and query * @returns A promise resolving to the database query results */ async function getList(config) { try { if (!config || !config.baseApiUrl) { throw new Error('Invalid configuration: baseApiUrl is required'); } if (!config.token) { throw new Error('Invalid configuration: token is required'); } if (!config.code) { throw new Error('code is required'); } console.log(`Querying database data for code: ${config.code}`); // Build the URL with the query parameter if provided let queryParams = []; // Add the query parameter if provided if (config.query) { queryParams.push(config.query); } // Add page_size parameter if provided if (config.page_size) { queryParams.push(`page_size=${config.page_size}`); } // Combine query parameters with '&' if multiple exist const queryString = queryParams.length > 0 ? `?${queryParams.join('&')}` : ''; // Encode the code parameter to handle spaces and special characters const encodedCode = encodeURIComponent(config.code); const url = `${config.baseApiUrl}/data/${encodedCode}/latest${queryString}`; console.log(`Request URL: ${url}`); const response = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${config.token}`, 'Content-Type': 'application/json' } }); if (!response.ok) { if (response.status === 401) { throw new Error('Authentication failed: Invalid or expired token'); } else if (response.status === 404) { throw new Error(`Database with code ${config.code} not found`); } throw new Error(`Failed to query database: ${response.statusText}`); } const data = await response.json(); console.log(`Successfully queried data for database code: ${config.code}`); return data; } catch (error) { console.error('Error querying database:', error); throw error; } }