/** * EDC Store Service * * Real EDC API client for Eclipse Dataspace Connector v3 * Handles all CRUD operations for Assets, Policies, and Contracts */ import type { Asset, AssetInput, PolicyDefinition, PolicyDefinitionInput, ContractDefinition, ContractDefinitionInput, QuerySpec, EdcStoreInterface } from '../types/edc-types'; export class EdcStore implements EdcStoreInterface { protected apiEndpoint: string; protected apiKey?: string; constructor(apiEndpoint: string, apiKey?: string) { this.apiEndpoint = apiEndpoint; this.apiKey = apiKey; } // ============================================================================ // Protected Helper Methods // ============================================================================ protected getHeaders(): HeadersInit { const headers: HeadersInit = { 'Content-Type': 'application/json', }; if (this.apiKey) { headers['X-Api-Key'] = this.apiKey; } return headers; } protected createQuerySpec(offset = 0, limit = 50): QuerySpec { return { '@context': { '@vocab': 'https://w3id.org/edc/v0.0.1/ns/' }, '@type': 'QuerySpec', offset, limit, filterExpression: [] }; } protected async handleResponse(response: Response): Promise { if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status}: ${errorText}`); } return await response.json(); } // ============================================================================ // Assets CRUD Operations // ============================================================================ async getAllAssets(): Promise { console.log('📦 Fetching assets from EDC Management API...'); try { const querySpec = this.createQuerySpec(); const response = await fetch(`${this.apiEndpoint}/v3/assets/request`, { method: 'POST', headers: this.getHeaders(), body: JSON.stringify(querySpec) }); const assets = await this.handleResponse(response); console.log(`✅ Loaded ${assets.length} assets from EDC API`); return Array.isArray(assets) ? assets : []; } catch (error: any) { console.error('❌ Failed to fetch assets from EDC API:', error); throw new Error(`Failed to fetch assets: ${error.message}`); } } async createAsset(assetData: AssetInput): Promise { console.log('🔨 Creating asset via EDC API:', assetData); try { const payload = { '@context': { '@vocab': 'https://w3id.org/edc/v0.0.1/ns/' }, '@type': 'Asset', '@id': assetData['@id'], properties: assetData.properties || {}, ...(assetData.dataAddress && { dataAddress: assetData.dataAddress }) }; const response = await fetch(`${this.apiEndpoint}/v3/assets`, { method: 'POST', headers: this.getHeaders(), body: JSON.stringify(payload) }); const result = await this.handleResponse(response); console.log('✅ Asset created successfully via EDC API'); return result; } catch (error: any) { console.error('❌ Failed to create asset via EDC API:', error); throw new Error(`Failed to create asset: ${error.message}`); } } async updateAsset(assetId: string, assetData: AssetInput): Promise { console.log('✏️ Updating asset via EDC API (delete + recreate approach):', assetId, assetData); try { // EDC v3 doesn't support direct PUT updates for assets // We need to delete the existing asset and create a new one // Step 1: Delete the existing asset console.log('🗑️ Deleting existing asset for update...'); await this.deleteAsset(assetId); // Step 2: Create the asset with updated data console.log('🔨 Creating updated asset...'); const result = await this.createAsset({ ...assetData, '@id': assetId }); console.log('✅ Asset updated successfully via EDC API (delete + recreate)'); return result; } catch (error: any) { console.error('❌ Failed to update asset via EDC API:', error); throw new Error(`Failed to update asset: ${error.message}`); } } async deleteAsset(assetId: string): Promise { console.log('🗑️ Deleting asset via EDC API:', assetId); try { const response = await fetch(`${this.apiEndpoint}/v3/assets/${assetId}`, { method: 'DELETE', headers: this.getHeaders() }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status}: ${errorText}`); } console.log('✅ Asset deleted successfully via EDC API'); } catch (error: any) { console.error('❌ Failed to delete asset via EDC API:', error); throw new Error(`Failed to delete asset: ${error.message}`); } } // ============================================================================ // Policies CRUD Operations // ============================================================================ async getAllPolicies(): Promise { console.log('📋 Fetching policies from EDC Management API...'); try { const querySpec = this.createQuerySpec(); const response = await fetch(`${this.apiEndpoint}/v3/policydefinitions/request`, { method: 'POST', headers: this.getHeaders(), body: JSON.stringify(querySpec) }); const policies = await this.handleResponse(response); console.log(`✅ Loaded ${policies.length} policies from EDC API`); return Array.isArray(policies) ? policies : []; } catch (error: any) { console.error('❌ Failed to fetch policies from EDC API:', error); throw new Error(`Failed to fetch policies: ${error.message}`); } } async createPolicy(policyData: PolicyDefinitionInput): Promise { console.log('🔨 Creating policy via EDC API:', policyData); try { const payload = { '@context': { '@vocab': 'https://w3id.org/edc/v0.0.1/ns/' }, '@type': 'PolicyDefinition', '@id': policyData['@id'], policy: policyData.policy }; const response = await fetch(`${this.apiEndpoint}/v3/policydefinitions`, { method: 'POST', headers: this.getHeaders(), body: JSON.stringify(payload) }); const result = await this.handleResponse(response); console.log('✅ Policy created successfully via EDC API'); return result; } catch (error: any) { console.error('❌ Failed to create policy via EDC API:', error); throw new Error(`Failed to create policy: ${error.message}`); } } async updatePolicy(policyId: string, policyData: PolicyDefinitionInput): Promise { console.log('✏️ Updating policy via EDC API (delete + recreate approach):', policyId, policyData); try { // Step 1: Delete the existing policy console.log('🗑️ Deleting existing policy for update...'); await this.deletePolicy(policyId); // Step 2: Create the policy with updated data console.log('🔨 Creating updated policy...'); const result = await this.createPolicy({ ...policyData, '@id': policyId }); console.log('✅ Policy updated successfully via EDC API (delete + recreate)'); return result; } catch (error: any) { console.error('❌ Failed to update policy via EDC API:', error); throw new Error(`Failed to update policy: ${error.message}`); } } async deletePolicy(policyId: string): Promise { console.log('🗑️ Deleting policy via EDC API:', policyId); try { const response = await fetch(`${this.apiEndpoint}/v3/policydefinitions/${policyId}`, { method: 'DELETE', headers: this.getHeaders() }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status}: ${errorText}`); } console.log('✅ Policy deleted successfully via EDC API'); } catch (error: any) { console.error('❌ Failed to delete policy via EDC API:', error); throw new Error(`Failed to delete policy: ${error.message}`); } } // ============================================================================ // Contracts CRUD Operations (Future Implementation) // ============================================================================ async getAllContracts(): Promise { console.log('📝 Fetching contract definitions from EDC Management API...'); try { const querySpec = this.createQuerySpec(); const response = await fetch(`${this.apiEndpoint}/v3/contractdefinitions/request`, { method: 'POST', headers: this.getHeaders(), body: JSON.stringify(querySpec) }); const contracts = await this.handleResponse(response); console.log(`✅ Loaded ${contracts.length} contract definitions from EDC API`); return Array.isArray(contracts) ? contracts : []; } catch (error: any) { console.error('❌ Failed to fetch contract definitions from EDC API:', error); throw new Error(`Failed to fetch contract definitions: ${error.message}`); } } async createContract(contractData: ContractDefinitionInput): Promise { console.log('🔨 Creating contract definition via EDC API:', contractData); try { const payload = { '@context': { '@vocab': 'https://w3id.org/edc/v0.0.1/ns/' }, '@type': 'ContractDefinition', '@id': contractData['@id'], accessPolicyId: contractData.accessPolicyId, contractPolicyId: contractData.contractPolicyId, ...(contractData.assetsSelector && { assetsSelector: contractData.assetsSelector }) }; const response = await fetch(`${this.apiEndpoint}/v3/contractdefinitions`, { method: 'POST', headers: this.getHeaders(), body: JSON.stringify(payload) }); const result = await this.handleResponse(response); console.log('✅ Contract definition created successfully via EDC API'); return result; } catch (error: any) { console.error('❌ Failed to create contract definition via EDC API:', error); throw new Error(`Failed to create contract definition: ${error.message}`); } } async updateContract(contractId: string, contractData: ContractDefinitionInput): Promise { console.log('✏️ Updating contract definition via EDC API (delete + recreate approach):', contractId, contractData); try { // Step 1: Delete the existing contract console.log('🗑️ Deleting existing contract definition for update...'); await this.deleteContract(contractId); // Step 2: Create the contract with updated data console.log('🔨 Creating updated contract definition...'); const result = await this.createContract({ ...contractData, '@id': contractId }); console.log('✅ Contract definition updated successfully via EDC API (delete + recreate)'); return result; } catch (error: any) { console.error('❌ Failed to update contract definition via EDC API:', error); throw new Error(`Failed to update contract definition: ${error.message}`); } } async deleteContract(contractId: string): Promise { console.log('🗑️ Deleting contract definition via EDC API:', contractId); try { const response = await fetch(`${this.apiEndpoint}/v3/contractdefinitions/${contractId}`, { method: 'DELETE', headers: this.getHeaders() }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status}: ${errorText}`); } console.log('✅ Contract definition deleted successfully via EDC API'); } catch (error: any) { console.error('❌ Failed to delete contract definition via EDC API:', error); throw new Error(`Failed to delete contract definition: ${error.message}`); } } }