/// import { ApiPayload, ComponentPayload, QueryError, SdkError, SyncComponentByExternalAliasInput, } from '@atlassian/forge-graphql-types'; import { CompassRequests } from '../../compass-requests'; import { COMPONENT_NOT_FOUND, FORGE_GRAPHQL_SDK_ERROR_SOURCE, NOT_FOUND_ERROR_TYPE, } from '../../helpers'; declare module '../../compass-requests' { interface CompassRequests { /** * Creates a component if it's external alias does not exist or updates the component if * the external alias does exist. * * **Required Oauth Scopes:** `write:component:compass`, `write:event:compass` */ syncComponentByExternalAlias( input: SyncComponentByExternalAliasInput, ): Promise>; } } CompassRequests.prototype.syncComponentByExternalAlias = async function ( this: CompassRequests, input: SyncComponentByExternalAliasInput, ) { const { cloudId, externalAlias, options, ...component } = input; let accErrors = [] as Array; let newComponent = {}; const { data, errors } = await this.getComponentByExternalAlias({ cloudId, ...externalAlias, options: { includeLinks: true, }, }); try { if ( errors.find((error: QueryError) => error.message === COMPONENT_NOT_FOUND) ) { if (options && options.createComponentIfNotFound) { const createComponentResp = await this.createComponent({ cloudId, externalAlias, ...component, }); newComponent = (createComponentResp && createComponentResp.data && createComponentResp.data.component) || {}; accErrors = accErrors.concat(createComponentResp.errors); } else { accErrors.push({ message: `Component with external alias id ${externalAlias.externalId} could not be found`, errorSource: FORGE_GRAPHQL_SDK_ERROR_SOURCE, errorType: NOT_FOUND_ERROR_TYPE, statusCode: 404, }); } } else if (errors.length === 0) { const currentComponent = data.component; const updateComponentResp = await this.updateComponent({ id: currentComponent.id, currentComponent, ...component, }); newComponent = updateComponentResp.data.component; accErrors = accErrors.concat(updateComponentResp.errors); } else { accErrors = accErrors.concat(errors); } } catch { accErrors = accErrors.concat(errors); } return { errors: accErrors, success: accErrors.length === 0, data: { component: newComponent }, } as ApiPayload; };