lodash#omit TypeScript Examples

The following examples show how to use lodash#omit. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: analysis-utils.ts    From prism-frontend with MIT License 7 votes vote down vote up
function mergeFeaturesByProperty(
  baselineFeatures: Feature[],
  aggregateData: Array<object>,
  id: string,
): Feature[] {
  const features = baselineFeatures.map(feature1 => {
    const aggregateProperties = aggregateData.filter(
      item => get(item, id) === get(feature1, ['properties', id]) && item,
    );

    const filteredProperties = aggregateProperties.map(filteredProperty => {
      // We use geometry from response. If not, use whole admin boundary.
      const filteredGeometry = get(filteredProperty, 'geometry');

      const propertyItems = filteredGeometry
        ? omit(filteredProperty, 'geometry')
        : filteredProperty;

      const properties = {
        ...get(feature1, 'properties'),
        ...propertyItems,
        impactValue: get(feature1, 'properties.data'),
      };

      const feature = filteredGeometry
        ? { ...feature1, geometry: filteredGeometry, properties }
        : { ...feature1, properties };

      return feature;
    });

    return filteredProperties;
  });

  return flatten(features);
}
Example #2
Source File: time-series.utils.ts    From aqualink-app with MIT License 7 votes vote down vote up
groupByMetricAndSource = <T extends TimeSeriesGroupable>(
  data: T[],
): TimeSeriesResponse<
  Omit<T, 'metric' | 'source' | 'surveyPointId' | 'surveyPointName'>
> => {
  return _(data)
    .groupBy('metric')
    .mapValues((grouped) => {
      return _(grouped)
        .groupBy('source')
        .mapValues((groupedData) => {
          const { surveyPointId, surveyPointName } = last(groupedData) || {};
          return merge(
            !isNull(surveyPointId)
              ? { surveyPoint: { id: surveyPointId, name: surveyPointName } }
              : {},
            {
              data: groupedData
                .filter((o) =>
                  typeof surveyPointId === 'number'
                    ? surveyPointId === o.surveyPointId
                    : true,
                )
                .map((o) =>
                  omit(
                    o,
                    'metric',
                    'source',
                    'surveyPointId',
                    'surveyPointName',
                  ),
                ),
            },
          );
        })
        .toJSON();
    })
    .toJSON();
}
Example #3
Source File: utils.tsx    From erda-ui with GNU Affero General Public License v3.0 7 votes vote down vote up
convertJobsParams = (jobParams: { image: string; resources: any }, isCustomScript: boolean, task: IStageTask) => {
  const { image, resources = {} } = jobParams || {};
  const filteredResources = omit(resources, 'disk');
  const readOnlyParams: any[] = [
    {
      name: 'image',
      readOnly: !isCustomScript,
      default: task.image || image,
    },
    {
      name: 'resources',
      type: 'struct',
      struct: Object.entries(filteredResources).map(([key, value]) => ({
        name: key,
        unit: resourceUnitMap[key],
        default: value,
      })),
    },
  ];
  return readOnlyParams;
}
Example #4
Source File: BullseyeMarker.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function BullseyeMarkerNonMemo(props: MarkerProps) {
  const icon = new Icon({
    iconUrl: 'bullseye.png',
    iconSize: [40, 40],
    iconAnchor: [20, 20]
  });

  return <Marker {...omit(props, 'onadd', 'icon')} icon={icon} />;
}
Example #5
Source File: RoleForm.tsx    From amplication with Apache License 2.0 6 votes vote down vote up
RoleForm = ({ onSubmit, defaultValues }: Props) => {
  const initialValues = useMemo(() => {
    const sanitizedDefaultValues = omit(
      defaultValues,
      NON_INPUT_GRAPHQL_PROPERTIES
    );
    return {
      ...INITIAL_VALUES,
      ...sanitizedDefaultValues,
    } as models.AppRole;
  }, [defaultValues]);

  return (
    <Formik
      initialValues={initialValues}
      validate={(values: models.AppRole) => validate(values, FORM_SCHEMA)}
      enableReinitialize
      onSubmit={onSubmit}
    >
      <Form childrenAsBlocks>
        <FormikAutoSave debounceMS={1000} />

        <NameField name="name" />

        <DisplayNameField
          name="displayName"
          label="Display Name"
          minLength={1}
        />

        <TextField name="description" label="Description" textarea rows={3} />
      </Form>
    </Formik>
  );
}
Example #6
Source File: helpers.ts    From S2 with MIT License 6 votes vote down vote up
createMockCellInfo = (
  cellId: string,
  { colIndex = 0, rowIndex = 0 } = {},
) => {
  const mockCellViewMeta: Partial<ViewMeta> = {
    id: cellId,
    colIndex,
    rowIndex,
    type: undefined,
    x: 0,
    y: 0,
  };
  const mockCellMeta = omit(mockCellViewMeta, ['x', 'y', 'update']);
  const mockCell = {
    ...mockCellViewMeta,
    getMeta: () => mockCellViewMeta,
    update: jest.fn(),
    getActualText: jest.fn(),
    getFieldValue: jest.fn(),
    hideInteractionShape: jest.fn(),
  } as unknown as S2CellType;

  return {
    mockCell,
    mockCellMeta,
  };
}
Example #7
Source File: regions.service.ts    From aqualink-app with MIT License 6 votes vote down vote up
async update(id: number, updateRegionDto: UpdateRegionDto) {
    const { parentId } = updateRegionDto;
    const updateParent =
      parentId !== undefined ? { parent: { id: parentId } } : {};
    const result = await this.regionsRepository.update(id, {
      ...omit(updateRegionDto, 'parentId'),
      ...updateParent,
    });
    if (!result.affected) {
      throw new NotFoundException(`Region with ID ${id} not found.`);
    }
    const updated = await this.regionsRepository.findOne(id);
    if (!updated) {
      throw new InternalServerErrorException('Something went wrong.');
    }
    return updated;
  }
Example #8
Source File: Accordion.tsx    From easy-email with MIT License 6 votes vote down vote up
export function Accordion(props: AccordionProps) {
  return (
    <MjmlBlock
      attributes={omit(props, ['data', 'children', 'value'])}
      value={props.value}
      type={BasicType.ACCORDION}
    >
      {props.children}
    </MjmlBlock>
  );
}
Example #9
Source File: TechInsightsDatabase.ts    From backstage with Apache License 2.0 6 votes vote down vote up
async getLatestSchemas(ids?: string[]): Promise<FactSchema[]> {
    const queryBuilder = this.db<RawDbFactSchemaRow>('fact_schemas');
    if (ids) {
      queryBuilder.whereIn('id', ids);
    }
    const existingSchemas = await queryBuilder.orderBy('id', 'desc').select();

    const groupedSchemas = groupBy(existingSchemas, 'id');
    return Object.values(groupedSchemas)
      .map(schemas => {
        const sorted = rsort(schemas.map(it => it.version));
        return schemas.find(it => it.version === sorted[0])!;
      })
      .map((it: RawDbFactSchemaRow) => ({
        ...omit(it, 'schema'),
        ...JSON.parse(it.schema),
        entityFilter: it.entityFilter ? JSON.parse(it.entityFilter) : null,
      }));
  }
Example #10
Source File: processor.ts    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
export function processFormValue(
  values = {},
  typeList: UnionPropertyType[]
): Record<string, any> {
  const formData: Record<string, any> = {};
  for (const [key, value] of Object.entries(values)) {
    if (isUseYamlParse({ key, value }, typeList)) {
      formData[key] = yaml(value);
    } else if (isUseMenuParse({ key, value }, typeList)) {
      formData[key] = calcMenuValue(value as string);
    } else {
      formData[key] = value;
    }
  }

  return {
    ...omit(formData, OTHER_FORM_ITEM_FIELD),
    ...(isEmpty(formData[OTHER_FORM_ITEM_FIELD])
      ? {}
      : formData[OTHER_FORM_ITEM_FIELD]),
  };
}
Example #11
Source File: BuilderDataManager.ts    From next-core with GNU General Public License v3.0 6 votes vote down vote up
private runAddNodeAction(detail: EventDetailOfNodeAdd): void {
    const { rootId, nodes, edges, wrapperNode } = this.data;
    const { nodeUid, parentUid, nodeUids, nodeData } = detail;

    const { nodes: addNodes, edges: addEdges } = getAppendingNodesAndEdges(
      omit(nodeData, [
        "parent",
      ]) as Partial<BuilderRouteOrBrickNode> as BuilderRouteOrBrickNode,
      nodeUid,
      this.templateSourceMap,
      this.getStoryList()
    );
    const newNodes = nodes.concat(addNodes);
    const newEdges = edges
      .concat({
        parent: parentUid,
        child: nodeUid,
        mountPoint: nodeData.mountPoint,
        sort: undefined,
        $$isTemplateDelegated: isParentExpandableTemplate(nodes, parentUid),
      })
      .concat(addEdges);

    const newData = {
      rootId,
      nodes: newNodes,
      edges: newEdges,
      wrapperNode,
    };
    this.data = {
      ...newData,
      edges: reorderBuilderEdges(newData, {
        parentUid,
        nodeUids,
      }),
    };
    this.triggerDataChange();
  }
Example #12
Source File: pipeline-yml-data-convert.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
pushTask = (options: IOption) => {
  const { task, taskGroup, item, actions, editConvertor, pipelineTaskAlias } = options;
  const otherTaskAlias = remove([...pipelineTaskAlias], (alias) => alias !== task.alias);
  const propertyViewDataSource = omit(task, ['alias', 'type', 'resources']);
  taskGroup.push({
    ...item,
    lineTo: ['all'],
    icon: 'wfw',
    editView: (editing: boolean) => {
      return (
        <EditStage
          editing={editing}
          actions={actions}
          task={task}
          otherTaskAlias={otherTaskAlias}
          onSubmit={editConvertor}
        />
      );
    },
    title: task.type,
    data: task,
    name: task.alias,
    content: () => {
      return <PropertyView dataSource={propertyViewDataSource} />;
    },
  });
}
Example #13
Source File: get-config.spec.ts    From js-client with MIT License 6 votes vote down vote up
describe('getMailServerConfig()', () => {
	it(
		'Should return the mail server config',
		integrationTest(async () => {
			const getMailServerConfig = makeGetConfig(TEST_BASE_API_CONTEXT);
			const updateMailServerConfig = makeUpdateConfig(TEST_BASE_API_CONTEXT);

			const config: MailServerConfig = {
				server: 'localhost',
				username: 'dev',
				port: 32,
				password: 'pwd',
				insecureSkipVerify: true,
				useTLS: false,
			};
			// update/create config
			const result = await updateMailServerConfig(config);
			expect(result).toBe(true);

			const createdConfig = await getMailServerConfig();
			// api doesn't return password on get so we omit it
			expect(createdConfig).toEqual(omit(config, 'password'));
		}),
	);
});
Example #14
Source File: ResizableTable.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
ResizableTitle = (props: Pick<ResizableProps, 'onResize' | 'width'>) => {
  const { onResize, width, ...restProps } = props;

  const prefixCls = usePrefixCls(TABLE_PREFIX_CLS);

  const separatorNode = useMemo(
    () => (
      // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
      <div
        className={`${prefixCls}-resizable-handle`}
        onClick={(event) => {
          event.preventDefault();
          event.stopPropagation();
        }}
      />
    ),
    [prefixCls]
  );

  if (!width) {
    return <th {...omit(restProps, ['columnIndex', 'columnKey'])} />;
  }

  return (
    <Resizable width={width} height={0} handle={separatorNode} onResize={onResize} minConstraints={[58, 0]}>
      <th {...omit(restProps, ['columnIndex', 'columnKey'])} />
    </Resizable>
  );
}
Example #15
Source File: withInject.tsx    From mo360-ftk with MIT License 6 votes vote down vote up
export default function withInject<TProps extends React.ComponentProps<any>>(
  Component: React.ComponentType<TProps>,
): React.ComponentType<TProps & IWithDiProps> {
  class ConsumeComponent extends React.Component<TProps & IWithDiProps, {}> {
    public render() {
      return (
        <diContext.Consumer>
          {(container) => {
            const props: TProps = omit(this.props, 'container') as any;
            return (
              <Component {...props} container={container}>
                {this.props.children}
              </Component>
            );
          }}
        </diContext.Consumer>
      );
    }
  }
  return ConsumeComponent;
}
Example #16
Source File: api.ts    From ovineherd with Apache License 2.0 6 votes vote down vote up
sysEditUserReqOpt = getReqOption(
  {
    ...relation.sys.user,
    apiName: ApiName.edit,
    '&': '$$',
  },
  {
    onPreRequest: (option) => {
      option.data = omit(option.data, ['username'])
      return option
    },
  }
)
Example #17
Source File: types.ts    From am-editor with MIT License 6 votes vote down vote up
colorProps = {
	engine: buttonProps.engine,
	name: buttonProps.name,
	content: {
		type: [String, Function] as PropType<
			| string
			| ((color: string, stroke: string, disabled?: boolean) => string)
		>,
		required: true,
	} as const,
	buttonTitle: String,
	dropdownTitle: String,
	command: buttonProps.command,
	autoExecute: buttonProps.autoExecute,
	disabled: buttonProps.disabled,
	...omit(colorPickerProps, 'engine'),
}
Example #18
Source File: read-default-config.spec.ts    From swc-node with MIT License 6 votes vote down vote up
test('should RESPECT SWC_NODE_PROJECT env', (t) => {
  const configPath = join(__dirname, 'tsconfig.spec.json')
  delete process.env.SWC_NODE_PROJECT
  delete process.env.TS_NODE_PROJECT
  process.env.SWC_NODE_PROJECT = configPath
  const defaultOptions = readDefaultTsConfig()
  const { config } = ts.readConfigFile(configPath, ts.sys.readFile)
  const { options } = ts.parseJsonConfigFileContent(config, ts.sys, dirname(configPath))
  t.deepEqual(omit(defaultOptions, 'files'), options)
})
Example #19
Source File: object-settings.ts    From prisma-nestjs-graphql with MIT License 6 votes vote down vote up
getObjectTypeArguments(options: Record<string, any>): string[] {
    const objectTypeOptions = merge({}, options);
    const resultArguments: any[] = [objectTypeOptions];
    const objectType = this.find(s => s.kind === 'ObjectType');
    if (objectType && isObject(objectType.arguments)) {
      const name = (objectType.arguments as PlainObject).name;
      merge(objectTypeOptions, omit(objectType.arguments, 'name'));
      if (name) {
        resultArguments.unshift(name);
      }
    }
    return resultArguments.map(x => JSON5.stringify(x));
  }
Example #20
Source File: competition.controller.ts    From wise-old-man with MIT License 6 votes vote down vote up
// POST /competitions
async function create(req: Request, res: Response, next: NextFunction) {
  try {
    const title = extractString(req.body, { key: 'title', required: true });
    const metric = extractString(req.body, { key: 'metric', required: true });
    const startsAt = extractDate(req.body, { key: 'startsAt', required: true });
    const endsAt = extractDate(req.body, { key: 'endsAt', required: true });
    const groupId = extractNumber(req.body, { key: 'groupId' });
    const groupVerificationCode = extractString(req.body, { key: 'groupVerificationCode' });
    const participants = extractStrings(req.body, { key: 'participants' });
    const teams = req.body.teams;

    const dto = { title, metric, startsAt, endsAt, groupId, groupVerificationCode, participants, teams };
    const competition = await service.create(dto);

    // Omit some secrets from the response
    const response = omit(
      competition,
      groupId ? ['verificationHash', 'verificationCode'] : ['verificationHash']
    );

    res.status(201).json(response);
  } catch (e) {
    next(e);
  }
}
Example #21
Source File: env.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 6 votes vote down vote up
sanitizeErrors = (
    errorString: string,
    environment?: Env
): string => {
    const env = environment || getEnv();

    const filteredEnv = omit(env, ['env', 'ethereumNetwork']);

    let sanitizedError = errorString;
    values(filteredEnv).forEach((val) => {
        if (val) {
            sanitizedError = sanitizedError.replace(val, 'redacted');
        }
    });

    return sanitizedError;
}
Example #22
Source File: index.ts    From free-swagger with MIT License 6 votes vote down vote up
prompt = async (questions: any[]) => {
  const results: Record<string, any> = {}
  for (const question of questions) {
    const condition = question.when
    if (condition && !condition(results)) {
      continue
    }
    const normalizeQuestion = omit(question, 'when')
    if (isFunction(normalizeQuestion.default)) {
      normalizeQuestion.default = normalizeQuestion.default(results)
    }
    const answer = (await inquirer.prompt(normalizeQuestion)) as Record<
      string,
      any
    >
    results[question.name] = answer[question.name]
    await question.callback?.(answer[question.name], results)
  }
  return results
}
Example #23
Source File: node.ts    From S2 with MIT License 5 votes vote down vote up
public toJSON() {
    return omit(this, ['config', 'hierarchy', 'parent', 'spreadsheet']);
  }
Example #24
Source File: sites.service.ts    From aqualink-app with MIT License 5 votes vote down vote up
async update(id: number, updateSiteDto: UpdateSiteDto): Promise<Site> {
    const { coordinates, adminIds, regionId, streamId } = updateSiteDto;
    const updateRegion =
      regionId !== undefined ? { region: { id: regionId } } : {};
    const updateStream =
      streamId !== undefined ? { region: { id: streamId } } : {};
    const updateCoordinates = coordinates
      ? {
          polygon: createPoint(coordinates.longitude, coordinates.latitude),
        }
      : {};

    const result = await this.sitesRepository
      .update(id, {
        ...omit(updateSiteDto, [
          'adminIds',
          'coordinates',
          'regionId',
          'streamId',
        ]),
        ...updateRegion,
        ...updateStream,
        ...updateCoordinates,
      })
      .catch(handleDuplicateSite);

    if (adminIds) {
      await this.updateAdmins(id, adminIds);
    }

    if (!result.affected) {
      throw new NotFoundException(`Site with ID ${id} not found.`);
    }

    const updated = await this.sitesRepository.findOne(id, {
      relations: ['admins'],
    });

    return updated!;
  }
Example #25
Source File: DatabaseManager.ts    From backstage with Apache License 2.0 5 votes vote down vote up
/**
   * Provides a Knex connection plugin config by combining base and plugin
   * config.
   *
   * This method provides a baseConfig for a plugin database connector. If the
   * client type has not been overridden, the global connection config will be
   * included with plugin specific config as the base. Values from the plugin
   * connection take precedence over the base. Base database name is omitted for
   * all supported databases excluding SQLite unless `pluginDivisionMode` is set
   * to `schema`.
   */
  private getConnectionConfig(
    pluginId: string,
  ): Partial<Knex.StaticConnectionConfig> {
    const { client, overridden } = this.getClientType(pluginId);

    let baseConnection = normalizeConnection(
      this.config.get('connection'),
      this.config.getString('client'),
    );

    if (
      client.includes('sqlite3') &&
      'filename' in baseConnection &&
      baseConnection.filename !== ':memory:'
    ) {
      throw new Error(
        '`connection.filename` is not supported for the base sqlite connection. Prefer `connection.directory` or provide a filename for the plugin connection instead.',
      );
    }

    // Databases cannot be shared unless the `pluginDivisionMode` is set to `schema`. The
    // `database` property from the base connection is omitted unless `pluginDivisionMode`
    // is set to `schema`. SQLite3's `filename` property is an exception as this is used as a
    // directory elsewhere so we preserve `filename`.
    if (this.getPluginDivisionModeConfig() !== 'schema') {
      baseConnection = omit(baseConnection, 'database');
    }

    // get and normalize optional plugin specific database connection
    const connection = normalizeConnection(
      this.config.getOptional(`${pluginPath(pluginId)}.connection`),
      client,
    );

    return {
      // include base connection if client type has not been overridden
      ...(overridden ? {} : baseConnection),
      ...connection,
    };
  }
Example #26
Source File: schemaEditor.ts    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function collectFields(
  list: SchemaItemProperty[],
  {
    requiredList,
    defaultData,
    importSet,
  }: {
    requiredList: string[];
    defaultData: Record<string, unknown>;
    importSet: Set<string>;
  },
  result: SchemaItemProperty[]
): void {
  list?.forEach((item) => {
    if (item.required) {
      requiredList.push(item.name || item.ref);
    }

    if (item.refRequired) {
      requiredList.push(...item.refRequired);
    }

    if (!isNil(item.default)) {
      defaultData[item.name] = item.default;
    }

    collectImport(item, importSet);

    const property = {
      ...omit(item, ["fields", "required", "refRequired", "default"]),
    } as SchemaItemProperty;

    result.push(property);

    if (item.fields && allowExpandFields(item.type)) {
      // 只有 object/object[] 类型的 fields 才需要提交, 其他 fields 仅为前台引用模型展示用
      property.fields = [];
      collectFields(
        item.fields,
        { requiredList, defaultData, importSet },
        property.fields
      );
    }
  });
}
Example #27
Source File: BuilderDataManager.ts    From next-core with GNU General Public License v3.0 5 votes vote down vote up
snippetApply(detail: EventDetailOfSnippetApply): void {
    this.redirectSnippetMountPoint(detail);
    const { rootId, nodes, edges, wrapperNode } = this.data;
    const { nodeDetails, parentUid, nodeUids } = detail;

    const newNodes: BuilderRuntimeNode[] = nodes.slice();
    const newEdges: BuilderRuntimeEdge[] = edges.slice();

    const walk = ({
      parentUid,
      nodeUid,
      nodeData,
      children,
    }: SnippetNodeDetail): void => {
      const { nodes: appendingNodes, edges: appendingEdges } =
        getAppendingNodesAndEdges(
          omit(nodeData, [
            "parent",
          ]) as Partial<BuilderRouteOrBrickNode> as BuilderRouteOrBrickNode,
          nodeUid,
          this.templateSourceMap,
          this.storyList
        );
      newNodes.push(...appendingNodes);
      newEdges.push(
        {
          parent: parentUid,
          child: nodeUid,
          mountPoint: nodeData.mountPoint,
          sort: nodeData.sort,
          $$isTemplateDelegated: isParentExpandableTemplate(
            newNodes,
            parentUid
          ),
        },
        ...appendingEdges
      );
      for (const item of children) {
        walk(item);
      }
    };

    for (const item of nodeDetails) {
      walk(item);
    }

    const newData = {
      rootId,
      nodes: newNodes,
      edges: newEdges,
      wrapperNode,
    };
    this.data = {
      ...newData,
      edges: reorderBuilderEdges(newData, {
        parentUid,
        nodeUids,
      }),
    };
    this.triggerDataChange();
    this.eventTarget.dispatchEvent(
      new CustomEvent(BuilderInternalEventType.SNIPPET_APPLY, { detail })
    );
  }
Example #28
Source File: responseBuilder.ts    From ts-di-starter with MIT License 5 votes vote down vote up
/**
   * Handle error response
   *
   * @param {Error} error error object or something and inheirits from it
   * @param {number} [codeOverride] optionally override the code specified in the error
   * @returns {{versions: *, code: number, status: string, dateTime: string, timestamp: number, message: *, data: *}}
   * @private
   */
  private errorResponse(error, codeOverride): ResponseInterface {
    // eslint-disable-next-line lodash/prefer-lodash-typecheck
    if (!(error instanceof Error)) {
      if (isString(error)) {
        return this.errorResponse(new Err(error), codeOverride);
      }

      return this.errorResponse(new Err('Unexpected error'), codeOverride);
    }

    const dateTime = DateTime.utc();
    const code = codeOverride || ResponseBuilder.getCodeFromError(error);
    const response = {
      code,
      status: HTTP_STATUS[code],
      dateTime: dateTime.toISO(),
      timestamp: dateTime.valueOf(),
    } as ResponseInterface;

    if (this.config.versions) {
      response.versions = this.config.versions;
    }

    if (error.message) {
      response.message = error.message;
    }

    const data = omit(error, ['message', 'code']);

    if (size(data) > 0) {
      response.data = data;
    }

    if (response.code >= HTTP_STATUS.INTERNAL_SERVER_ERROR) {
      log.error(`500+ error: ${error.stack}`);
    }

    return response;
  }
Example #29
Source File: conversation-repository.spec.ts    From linkedin-private-api with MIT License 5 votes vote down vote up
describe('getConversation', () => {
  const createRequestUrl = (conversationId: string) => `${requestUrl}/${conversationId}`;

  it('should get conversation by conversation id', async () => {
    const conversationId = faker.datatype.uuid();
    const { response, resultConversation } = createGetConversationResponse();

    when(axios.get(createRequestUrl(conversationId), { params: reqParams })).thenResolve({ data: response });

    const client = await new Client().login.userPass({ username, password });
    const conversation = await client.conversation.getConversation({ conversationId });

    expect(omit(conversation, ['conversationId', 'participants'])).toEqual(resultConversation);
  });

  it('should add conversation id to the result conversation', async () => {
    const conversationId = faker.datatype.uuid();
    const { response, resultConversation } = createGetConversationResponse();
    resultConversation.entityUrn = `urn:li:fs_conversation:${conversationId}`;

    when(axios.get(createRequestUrl(conversationId), { params: reqParams })).thenResolve({ data: response });

    const client = await new Client().login.userPass({ username, password });
    const conversation = await client.conversation.getConversation({ conversationId });

    expect(conversation.conversationId).toEqual(conversationId);
  });

  it('should add participants to the result conversation', async () => {
    const conversationId = faker.datatype.uuid();
    const { response, resultConversation, resultProfiles } = createGetConversationResponse();
    const profileIds = resultProfiles.map(profile => profile.entityUrn.replace('urn:li:fs_miniProfile:', ''));
    const participantIds = profileIds.map(profileId => `urn:li:fs_messagingMember:(${faker.datatype.number()},${profileId})`);
    resultConversation['*participants'] = participantIds;

    when(axios.get(createRequestUrl(conversationId), { params: reqParams })).thenResolve({ data: response });

    const client = await new Client().login.userPass({ username, password });
    const conversation = await client.conversation.getConversation({ conversationId });

    expect(conversation.participants[0].entityUrn).toEqual(resultProfiles[0].entityUrn);
    expect(conversation.participants[0].profileId).toEqual(profileIds[0]);
    expect(conversation.participants[1].entityUrn).toEqual(resultProfiles[1].entityUrn);
    expect(conversation.participants[1].profileId).toEqual(profileIds[1]);
  });
});