All files / src/api/connector/internal rest.js

73.86% Statements 113/153
43.84% Branches 32/73
82.86% Functions 29/35
74.15% Lines 109/147

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391                                                4x 1x 4x 4x   4x         4x 4x   4x   4x     4x   1x     4x 1x 1x 1x     1x 15x   15x 30x 30x       15x     1x     4x 4x 4x 4x   4x     4x 1x 1x           1x               4x 1x   1x   1x 2x   2x   2x     1x     4x                           4x 1x 1x     4x 1x   1x 1x 1x     1x     4x 1x           2x 1x 1x           1x   1x 1x     1x           4x 1x 1x 2x           2x     1x         1x           4x   1x 6x                         6x     6x     4x                                                                                                     4x 1x     1x 1x                                         1x 1x 1x 1x   1x       1x   1x 1x   1x       1x 1x 1x             1x             1x 1x   1x       1x             2x     2x 1x   1x     2x       2x   2x                     1x           1x     1x     1x 1x   1x   1x 1x 1x   1x                
/*
Reserved for Ride Core connector.
*/
import http from 'axios';
import {
  assign,
  each,
  filter,
  find,
  isArray,
  isNil,
  keyBy,
  keys,
  map,
  has,
  omit,
  omitBy,
  forIn,
  toLower,
  uniq,
} from 'lodash';
import { getSortParam } from '../common';
import { uriParser } from '../../../utility';
 
const formatSourceSchema = (record, view) => {
  const formatted = map(view.fields, (field) => {
    const viewField = field;
    viewField.name = field.displayName;
 
    Iif (viewField.dependencyPath) {
      viewField.type = 'relation';
      return viewField;
    }
 
    const fieldSchema = find(record.fields, { id: field.displayFieldId });
    fieldSchema.name = field.displayName;
 
    viewField.type = fieldSchema.type;
 
    return viewField;
  });
 
  const filteredFields = filter(formatted, field => field.type !== 'primary');
 
  return filteredFields;
};
 
const formatResponse = (response) => {
  const responseMetadataFields = response.metadata.schema.fields;
  const fields = response.data;
  const formatedResponse = { metadata: omit(response.metadata, ['schema']), data: [], pagination: response.pagination };
  let formatedField;
 
  map(fields, (field) => {
    formatedField = {};
 
    forIn(field, (value, key) => {
      Eif (has(responseMetadataFields, key)) {
        formatedField[responseMetadataFields[key].displayName] = value;
      }
    });
 
    formatedResponse.data.push(formatedField);
  });
 
  return formatedResponse;
};
 
const getBaseUrl = (connectorOptions, connectorType, type) => {
  const api = connectorType.options.endpoint;
  const serviceEndpoint = api[type];
  const url = `${serviceEndpoint}/spaces/${connectorOptions.space}`;
 
  return url;
};
 
const getChangeMethod = (options) => {
  const action = toLower(options.action);
  switch (action) {
    case 'delete':
      return action;
    case 'update':
      return 'patch';
    default:
      return 'post';
  }
};
 
/*
This will most probably be changed, as it's not certain
yet in which form will the payload be sent from UI components
*/
const getChangePayload = (payload, schema) => {
  Iif (!payload) return null;
 
  const change = {};
 
  each(payload, (value, key) => {
    const schemaField = find(schema, { mapName: key });
 
    const fieldValue = schemaField.type === 'number' && value
      ? parseFloat(value) : value;
    change[schemaField.displayFieldId] = fieldValue;
  });
 
  return change;
};
 
const getInstalledVersions = (baseUrl, versions) => {
  const url = `${baseUrl}/installed-schema-versions`;
  const params = {
    versionIds: versions.join(','),
  };
 
  return http.get(url, {
    params,
  }).then((response) => {
    const result = response.data;
    return result.data;
  });
};
 
const getLatestSchema = (baseUrl, dataPackageId) => {
  const latestSchemaUrl = `${baseUrl}/data-packages/${dataPackageId}/schema-versions/uncommitted`;
  return http.get(latestSchemaUrl).then(response => response.data);
};
 
const getClientParams = (optionParams = {}) => {
  const clientParams = {};
 
  clientParams.size = optionParams.size || optionParams.pageSize;
  clientParams.page = optionParams.page || optionParams.currentPage;
  clientParams.sort = optionParams.sortBy && optionParams.sortBy.id
    ? getSortParam(optionParams.sort, optionParams.sortBy.id) : null;
 
  return omitBy(clientParams, isNil);
};
 
const getSourceDataReqDefinition = (connector, source, options) => {
  const baseUrl = getBaseUrl(
    connector.options,
    connector.type,
    'read',
  );
 
  const fields = map(source.schema, field => field.id);
  const url = `${baseUrl}/schema-versions/${source.meta.schemaVersion}/records/${source.meta.record}/instances`;
  const params = {
    viewId: source.id,
    fields: JSON.stringify(fields),
    includeFieldMetadata: true,
  };
 
  assign(params, getClientParams(options.params.pagination));
 
  Eif (source.filters && source.filters.length > 0) {
    params.filters = JSON.stringify(source.filters);
  }
 
  return {
    url,
    params,
  };
};
 
const getSourceSeedReqDefinition = (connector, source, options) => {
  const api = connector.type.options.endpoint.read;
  const schema = map(source.schema, (field) => {
    const fieldData = {
      name: field.name,
      type: field.type,
      multiValue: field.multiValue,
    };
 
    return fieldData;
  });
 
  const params = {
    numRecords: options.params && options.params.numRecords ? options.params.numRecords : 10,
    schema: JSON.stringify({ name: 'test', schema }),
  };
 
  return {
    url: `${api}/misc/seed`,
    params,
  };
};
 
const formatViewModels = (views) => {
  // Attach necessary data for READ & WRITE implementation
  const viewModels = map(views, (view) => {
    const viewData = {
      id: view.id,
      name: view.name,
      model: view.name,
      meta: {
        dataPackage: view.dataPackageId,
        dataPackageName: view.dataPackageName,
        record: view.rootRecordId,
        schemaVersion: view.versionId,
        schemaTag: view.versionTag,
      },
    };
 
    return viewData;
  });
 
  return keyBy(viewModels, item => item.id);
};
 
const getSavedViewModels = (viewModels, connector, baseUrl) => {
  const missingVersions = [];
  const result = map(connector.sources, (item) => {
    const source = item;
    const sourceVersion = source.meta.schemaVersion;
    const existsInNew = viewModels[source.id];
    const versionChanged = existsInNew
      ? existsInNew.meta.schemaVersion !== sourceVersion : true;
 
    source.disabled = !existsInNew;
 
    if (versionChanged && existsInNew) {
      source.meta.schemaVersions = [{
        schemaVersion: existsInNew.meta.schemaVersion,
        schemaTag: existsInNew.meta.schemaTag,
      }];
    }
 
    if (!existsInNew || versionChanged) {
      missingVersions.push(sourceVersion);
    }
 
    return source;
  });
 
  if (missingVersions.length === 0) {
    return Promise.resolve(result);
  }
 
  return getInstalledVersions(baseUrl, uniq(missingVersions)).then((versions) => {
    const finalResult = map(result, (item) => {
      const source = item;
 
      const installedVersion = find(versions, {
        schemaVersion: { versionId: source.meta.schemaVersion },
      });
      const installedSource = installedVersion
        && find(installedVersion.schemaVersion.schema.views, { id: source.id });
 
      source.installed = !!installedVersion && !!installedSource;
      if (source.installed) {
        source.meta.schemaTag = installedVersion.schemaVersion.versionTag;
      }
 
      return source;
    });
 
    return finalResult;
  });
};
 
const getSourcesRequestParams = (sources, { savedOnly, pagination = {}, search }) => {
  const viewModelNames = search && search.length ? [search] : undefined;
 
  // When fetching full result set, use incoming pagination
  Eif (!savedOnly) {
    return {
      page: pagination.page,
      size: pagination.size,
      viewModelNames,
    };
  }
 
  const sourcesIds = keys(sources);
 
  // When fetching info about already saved sources,
  // construct new pagination and filter it by view model ids
  return {
    page: 1,
    size: sourcesIds.length,
    viewModelIds: sourcesIds,
    viewModelNames,
  };
};
 
export default {
  changeSourceData(connector, source, options) {
    const baseUrl = getBaseUrl(connector.options, connector.type, 'write');
    const method = getChangeMethod(options);
    const payload = getChangePayload(options.payload, source.schema);
    let url = `${baseUrl}/schema-versions/${source.meta.schemaVersion}/records/${source.meta.record}`;
 
    Iif (payload.recordInstanceId) {
      url += `/instances/${payload.recordInstanceId}`;
    }
 
    return http[method](url, payload).then((response) => {
      // return result with field names from original payload
      const result = options.payload;
      result.id = response.data.recordInstanceId;
 
      return result;
    });
  },
  getSources(connector, options) {
    const { savedOnly } = options;
    const requestParams = getSourcesRequestParams(connector.sources, options);
    const baseUrl = getBaseUrl(
      connector.options,
      connector.type,
      'blueprint',
    );
 
    // Get available view models from all data packages in space
    return http.get(`${baseUrl}/available-view-models`, {
      params: {
        types: ['uncommitted', 'foreign'],
        ...requestParams,
      },
      paramsSerializer: uriParser.encode,
    }).then((response) => {
      const viewModels = response.data.data;
      const formattedViewModels = formatViewModels(viewModels);
 
      Iif (savedOnly) {
        return getSavedViewModels(formattedViewModels, connector, baseUrl);
      }
 
      return {
        data: formattedViewModels,
        pagination: response.data.pagination,
      };
    });
  },
  getSourceData(connector, source, options) {
    const isSeed = options.seed;
    let requestDefinition;
 
    if (isSeed) {
      requestDefinition = getSourceSeedReqDefinition(connector, source, options);
    } else {
      requestDefinition = getSourceDataReqDefinition(connector, source, options);
    }
 
    return http.get(requestDefinition.url, {
      params: requestDefinition.params,
      paramsSerializer: uriParser.encode,
    }).then((response) => {
      const result = isSeed ? response.data : formatResponse(response.data);
 
      return {
        [source.name]: {
          items: result.data,
          metadata: result.metadata, // todo do we need this?
          pagination: result.pagination,
        },
      };
    });
  },
  getSourceSchema(connector, source) {
    let schemaRequest;
    const baseUrl = getBaseUrl(
      connector.options,
      connector.type,
      'blueprint',
    );
 
    Iif (source.installed && source.disabled) {
      schemaRequest = getInstalledVersions(baseUrl, [source.meta.schemaVersion]);
    } else {
      schemaRequest = getLatestSchema(baseUrl, source.meta.dataPackage);
    }
 
    return schemaRequest.then((response) => {
      let result = isArray(response) ? response[0] : response;
 
      Iif (result && result.schemaVersion) result = result.schemaVersion;
 
      const { records, views } = result.schema;
      const viewSchema = find(views, { id: source.id });
      const schema = find(records, { id: source.meta.record });
 
      return {
        id: source.id,
        schema: formatSourceSchema(schema, viewSchema),
        meta: source.meta,
      };
    });
  },
};