lodash#merge TypeScript Examples

The following examples show how to use lodash#merge. 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: server-utils.ts    From prism-frontend with MIT License 7 votes vote down vote up
/**
 * Load available dates for WMS and WCS using a serverUri defined in prism.json and for GeoJSONs (point data) using their API endpoint.
 *
 * @return a Promise of Map<LayerID (not always id from LayerProps but can be), availableDates[]>
 */
export async function getLayersAvailableDates(): Promise<AvailableDates> {
  const wmsServerUrls: string[] = get(appConfig, 'serversUrls.wms', []);
  const wcsServerUrls: string[] = get(appConfig, 'serversUrls.wcs', []);

  const pointDataLayers = Object.values(LayerDefinitions).filter(
    (layer): layer is PointDataLayerProps => layer.type === 'point_data',
  );

  const layerDates: AvailableDates[] = await Promise.all([
    ...wmsServerUrls.map(url => getWMSCapabilities(url)),
    ...wcsServerUrls.map(url => getWCSCoverage(url)),
    ...pointDataLayers.map(async layer => ({
      [layer.id]: await getPointDataCoverage(layer),
    })),
  ]);

  return merge({}, ...layerDates);
}
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: index.ts    From openapi-cop with MIT License 6 votes vote down vote up
constructor(args: OpenAPISchemaValidatorArgs) {
    const v = new Ajv({ schemaId: 'auto', allErrors: true });
    v.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
    const schema = merge(
      {},
      args.version === 'openapi-2.0' ? openapi2Schema : openapi3Schema,
      args ? args.extensions : {},
    );
    v.addSchema(schema);
    this.validator = v.compile(schema);
  }
Example #4
Source File: defaultPage.ts    From freedeck-configurator with GNU General Public License v3.0 6 votes vote down vote up
getDefaultDisplay: (
  options?: IDefaultImageDisplayOptions
) => IDisplay = (options) =>
  merge<IDisplay, IDefaultImageDisplayOptions | undefined>(
    {
      hasOriginalImage: true,
      imageSettings: {
        brightness: 0,
        contrast: 0,
        whiteThreshold: 64,
        blackThreshold: 192,
        dither: false,
        invert: false,
      },
      textSettings: {
        font: fontMedium,
        text: "",
      },
      textWithIconSettings: {
        iconWidthMultiplier: 0.35,
      },
      isGeneratedFromDefaultBackImage: false,
      previousDisplay: undefined,
      previousPage: undefined,
    },
    options
  )
Example #5
Source File: index.tsx    From prism-frontend with MIT License 6 votes vote down vote up
styles = () =>
  createStyles({
    dateItemFull: {
      ...DATE_ITEM_STYLES,
      borderLeft: '1px solid white',
      height: 36,
    },

    dateItem: merge(DATE_ITEM_STYLES, {
      '&:hover': {
        '& $dayItem': {
          borderLeft: 0,
        },
      },
    }),

    dateItemLabel: {
      position: 'absolute',
      top: 22,
      textAlign: 'left',
      paddingLeft: 5,
      minWidth: 80,
    },

    dayItem: {
      height: 10,
      borderLeft: '1px solid white',
    },

    dateAvailable: {
      position: 'absolute',
      top: 0,
      backgroundColor: 'white',
      height: 5,
      width: TIMELINE_ITEM_WIDTH,
      opacity: 0.6,
    },
  })
Example #6
Source File: BitcoinJsonRpcError.ts    From bitcoin-json-rpc with MIT License 6 votes vote down vote up
constructor(inner: Error & { data?: any }, executed: boolean | null, data?: any) {
    super(inner.message);

    this.executed = executed;
    this.data = merge(
      {},
      inner.data,
      {
        bitcoinJsonRpc: {
          executed,
        },
      },
      data
    );
  }
Example #7
Source File: theme.ts    From amplication with Apache License 2.0 6 votes vote down vote up
palette = createPalette(
  merge({}, defaultTheme.palette, {
    primary: {
      main: "#20a4f3",
    },
    secondary: {
      main: "#7950ed",
    },
    error: {
      main: "#e93c51",
    },
    warning: {
      main: "#f6aa50",
    },
    info: {
      main: "#144bc1",
    },
    success: {
      main: "#31c587",
    },
  })
)
Example #8
Source File: table-facet-spec.ts    From S2 with MIT License 6 votes vote down vote up
describe('Table Mode Facet Test With Zero Height', () => {
  const ss: SpreadSheet = new MockSpreadSheet();
  const dataSet: TableDataSet = new MockTableDataSet(ss);
  ss.options = merge({}, assembleOptions(), {
    width: 0,
    height: 0,
  });
  const facet: TableFacet = new TableFacet({
    spreadsheet: ss,
    dataSet,
    ...assembleDataCfg().fields,
    ...merge({}, assembleOptions()),
    ...DEFAULT_STYLE,
    columns: ['province', 'city', 'type', 'sub_type', 'price'],
  });

  test('should get correct panelBBox', () => {
    const panelBBox = facet.panelBBox;
    expect(panelBBox.width).toBe(0);
    expect(panelBBox.height).toBe(0);
  });

  test('should get correct initial scroll position', () => {
    const { scrollX, scrollY } = facet.getScrollOffset();
    expect(scrollX).toBe(0);
    expect(scrollY).toBe(0);
  });
});
Example #9
Source File: index.tsx    From easy-email with MIT License 6 votes vote down vote up
AccordionElement = createBlock<IAccordionElement>({
  name: 'Accordion element',
  type: BasicType.ACCORDION_ELEMENT,
  create: (payload) => {
    const defaultData: IAccordionElement = {
      type: BasicType.ACCORDION_ELEMENT,
      data: {
        value: {},
      },
      attributes: {
        'icon-align': 'middle',
        'icon-height': '32px',
        'icon-width': '32px',

        'icon-position': 'right',
        padding: '10px 25px 10px 25px',
      },
      children: [],
    };
    return merge(defaultData, payload);
  },
  validParentType: [BasicType.ACCORDION],
})
Example #10
Source File: DatabaseManager.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
   * Provides the knexConfig which should be used for a given plugin.
   *
   * @param pluginId - Plugin to get the knexConfig for
   * @returns The merged knexConfig value or undefined if it isn't specified
   */
  private getAdditionalKnexConfig(pluginId: string): JsonObject | undefined {
    const pluginConfig = this.config
      .getOptionalConfig(`${pluginPath(pluginId)}.knexConfig`)
      ?.get<JsonObject>();

    const baseConfig = this.config
      .getOptionalConfig('knexConfig')
      ?.get<JsonObject>();

    return merge(baseConfig, pluginConfig);
  }
Example #11
Source File: index.ts    From reaction-role with MIT License 6 votes vote down vote up
public async importConfig(config: IConfig): Promise<IConfig> {
		merge(this.config, config);
		if (this.on_get) {
			const saved = (await this.on_get()) || {};
			merge(saved, this.config);
			if (this.on_set) {
				await this.on_set(saved);
			}
		}
		return this.config;
	}
Example #12
Source File: api.ts    From brick-design with MIT License 6 votes vote down vote up
handleResponseState = (response: Payload) => {
  const state = {};
  const { isPageState, isNotState, data, status } = response;
  if (!isNotState && status === 0) {
    if (isPageState) {
      merge(state, { pageState: data });
    } else {
      merge(state, { state: data });
    }
  }
  return state;
}
Example #13
Source File: Branding.ts    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
function getBrandingData(receivedBranding?: { [key: string]: any }): BrandingData {
  let branding: BrandingData = Object.assign({}, BRANDING_DEFAULT);

  if (receivedBranding && Object.keys(receivedBranding).length > 0) {
    branding = merge(branding, receivedBranding);
  }
  // resolve asset paths
  const assetTitles: Array<keyof BrandingData> = ['logoFile', 'logoTextFile'];
  assetTitles.forEach((asset: string) => {
    const path = branding[asset] as string;
    if (path.startsWith(ASSET_PREFIX)) {
      return;
    }
    branding[asset] = ASSET_PREFIX + branding[asset];
  });

  return branding;
}
Example #14
Source File: index.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
formatFormValues(values: Record<string, any>): Record<string, any> {
    // 格式化表单的数据
    // 日期相关的数据传出为 moment 对象,格式化为指定形式的 string
    const formatValues = Object.entries(values).reduce<Record<string, any>>(
      (acc, [key, value]) => {
        const valueType = this.valueTypes?.[key];
        if (typeof valueType === "string") {
          const matches = valueType.match(/^moment(?:\|(.+))?$/);
          if (matches && !isNil(value)) {
            value = moment(value).format(matches[1]);
          }
        }

        acc[key] = value;
        return acc;
      },
      {}
    );

    // 合并表单常量值
    return merge(cloneDeep(this.staticValues), formatValues);
  }
Example #15
Source File: ModalElement.ts    From next-core with GNU General Public License v3.0 6 votes vote down vote up
/**
   * 打开模态框。
   *
   * @param e - 事件。
   */
  openModal = (e?: CustomEvent): void => {
    if (e) {
      if (typeof e.detail === "object" && !Array.isArray(e.detail)) {
        merge(this, e.detail);
      } else {
        merge(this, { detail: e.detail });
      }
    }
    this.isVisible = true;
    this._render();
  };
Example #16
Source File: i18n-utils.ts    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
extractAllI18nD = async (
  isExternal: boolean,
  originalResource: Obj<[Obj<Obj>, Obj<Obj>]>,
  translatedWords: Obj,
  untranslatedWords: Set<string>,
) => {
  const dirMap = isExternal ? externalSrcDirMap : internalSrcDirMap;
  const promises = Object.values(dirMap)
    .flat()
    .map((srcPath) => {
      return new Promise<void>((resolve) => {
        const moduleName = Object.keys(dirMap).find((key) => dirMap[key].includes(srcPath));
        const [zhResource] = originalResource[moduleName!];
        // first step is to find out the content that needs to be translated, and assign the content to two parts: untranslated and translated
        walker({
          root: srcPath,
          excludePath: excludeSrcDirs,
          dealFile: (...args) => {
            extractUntranslatedWords.apply(null, [
              ...args,
              !isExternal ? merge(zhResource, originalResource.default[0]) : zhResource,
              translatedWords,
              untranslatedWords,
              resolve,
            ]);
          },
        });
      });
    });
  await Promise.all(promises);

  // After all files are traversed, notTranslatedWords is written to temp-zh-words in its original format
  if (untranslatedWords.size > 0) {
    const enMap: Obj = {};
    untranslatedWords.forEach((word) => {
      enMap[word] = '';
    });
    fs.writeFileSync(tempFilePath, JSON.stringify(enMap, null, 2), 'utf8');
    logSuccess(`Finish writing to the temporary file ${chalk.green('[temp-zh-words.json]')}`);
  }
  // translatedWords write to [temp-translated-words.json]
  if (Object.keys(translatedWords).length > 0) {
    fs.writeFileSync(tempTranslatedWordPath, JSON.stringify(translatedWords, null, 2), 'utf8');
    logSuccess(`Finish writing to the temporary file ${chalk.green('[temp-translated-words.json]')}`);
  }
}
Example #17
Source File: vite.config.ts    From fect with MIT License 6 votes vote down vote up
useDevConfig = async (): Promise<InlineConfig> => {
  const { userConfig } = await resolveConfig()
  const { port, plugins, viteConfigure } = userConfig

  const presetConfig = {
    root: CWD,
    resolve: {
      extensions: VITE_RESOLVE_EXTENSIONS,
      alias: {}
    },
    server: {
      port
    },
    plugins: [Vue({ include: [/\.vue$/, /\.md$/] }), Jsx(), ...plugins]
  }

  return merge(presetConfig, viteConfigure)
}
Example #18
Source File: utils.ts    From gant-design with MIT License 6 votes vote down vote up
export function setGlobalConfig(config: any) {
  merge(globalConfig, config);
}
Example #19
Source File: plugin.ts    From lift with MIT License 6 votes vote down vote up
private registerConstructsSchema() {
        (
            this.constructsSchema.patternProperties[CONSTRUCT_ID_PATTERN].allOf as unknown as Record<string, unknown>[]
        ).push({
            oneOf: this.getAllConstructClasses().map((Construct) => {
                return merge(this.defineSchemaWithType(Construct.type, Construct.schema), {
                    properties: { extensions: { type: "object" } },
                });
            }),
        });
    }
Example #20
Source File: ServerStorage.ts    From jitsu with MIT License 6 votes vote down vote up
async saveUserInfo(data: Partial<UserDTO>): Promise<void> {
    let current: UserDTO = await this.backendApi.get(`/users/info`)
    let mergedUserInfo = merge(
      current,
      sanitize(data, {
        // TODO _email is temporary
        allow: [
          "_emailOptout",
          "_name",
          "_forcePasswordChange",
          "_name",
          "_onboarded",
          "_suggestedInfo",
          "_project",
          "_email",
        ],
      })
    )
    console.log("Saving user info", mergedUserInfo)
    return this.backendApi.post(`/users/info`, mergedUserInfo)
  }
Example #21
Source File: Provider.tsx    From mo360-ftk with MIT License 6 votes vote down vote up
private bindServices = once((container: IDiContainer) => {
    container.bind<ConfigService>(ConfigService).toDynamicValue((context: IDiContext) => {
      let config: IConfigData = defaultConfig;
      try {
        const boundContainer = findBoundContainer(context.container, ConfigService);
        // prevent a recursion loop if the configuration is bound in our own container
        if (boundContainer.id !== context.container.id) {
          config = boundContainer.get(ConfigService).getConfig();
        }
      } catch {
        // swallow the error; it means we have no config already bound and fallback to use the defaultConfig
      }

      const overwrittenConfig = this.props.config || {};
      const merged = merge({ ...config }, overwrittenConfig);

      return new ConfigService(merged);
    });
  });
Example #22
Source File: dict.monad.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Recursive merge of two Dicts
     * ```ts
     * const foo = Dict.from({foo: true, baz: {key1: 'foo'}});
     * const bar = Dict.from({bar: 1, baz: {key2: 'bar'}});
     * const fooBar = foo.merge(bar);
     * fooBar.toObject() // {foo: true, bar: 1, baz: {key1: 'foo', key2: 'bar'}}
     * ```
     */
    merge<O extends Dict>(other: O): Dict<T & O> {
        // @ts-ignore
        return Dict.from(merge({}, this.toObject(), Dict.isDict(other) ? other.toObject() : other));
    }
Example #23
Source File: schema.ts    From am-editor with MIT License 6 votes vote down vote up
/**
	 * 过滤满足node节点规则的属性和样式
	 * @param node 节点,用于获取规则
	 * @param attributes 属性
	 * @param styles 样式
	 * @param apply 是否把过滤的属性和样式应用到节点上
	 * @returns
	 */
	filter(
		node: NodeInterface,
		attributes: { [k: string]: string },
		styles: { [k: string]: string },
		apply: boolean = false,
	) {
		const rule = this.getRule(node);
		if (!rule) return;
		const { globals } = this.data;
		const globalRule = globals[rule.type] ? rule.type : undefined;
		const allRule = Object.assign({}, rule, {
			attributes: merge(
				{},
				rule.attributes,
				globalRule ? globals[globalRule] : {},
			),
		});
		this.filterAttributes(
			attributes,
			allRule,
			apply ? (name) => node.removeAttributes(name) : undefined,
		);
		this.filterStyles(
			styles,
			allRule,
			apply ? (name) => node.css(name, '') : undefined,
		);
	}
Example #24
Source File: storyblok.ts    From nextjs-bigcommerce-starter with MIT License 6 votes vote down vote up
function initEventListeners(story: StoryData, setStory: any) {
  if (window.storyblok) {
    window.storyblok.init({
      accessToken: process.env.STORYBLOK_TOKEN
    });
    
    window.storyblok.on(["change", "published"], () => location.reload(true));

  const inputFunction = (event: any, s: any) => {
    const content = s.content ? s.content : s
    if (event && event.story.content._uid === content._uid) { 
        event.story.content =  window.storyblok.addComments(event.story.content, event.story.id)

        if(event.story.content.body) {
          const mergedBody: any[] = event.story.content.body?.map((item: StoryblokComponent<string>) => {
            let oldItem = content.body.find((itemWithData: StoryblokComponent<string>) => itemWithData._uid === item._uid)
            return merge(oldItem, item)
          }).filter(Boolean)

          event.story.content.body = mergedBody
        }
        setStory(event.story)
    }
  }

    // we will debounce the funcction since we're doing some data processing inside
    window.storyblok.on('input', debounce((e) => inputFunction(e, story), 300))
  }
}
Example #25
Source File: ls-config.ts    From language-tools with MIT License 6 votes vote down vote up
/**
     * Updates config.
     */
    update(config: DeepPartial<LSConfig>): void {
        // Ideally we shouldn't need the merge here because all updates should be valid and complete configs.
        // But since those configs come from the client they might be out of synch with the valid config:
        // We might at some point in the future forget to synch config settings in all packages after updating the config.
        this.config = merge({}, defaultLSConfig, this.config, config);
        // Merge will keep arrays/objects if the new one is empty/has less entries,
        // therefore we need some extra checks if there are new settings
        if (config.svelte?.compilerWarnings) {
            this.config.svelte.compilerWarnings = config.svelte.compilerWarnings;
        }

        this.listeners.forEach((listener) => listener(this));
    }
Example #26
Source File: i18next-electron-fs-backend.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
// Merges objects together
function mergeNestedI18NObject<T extends Object<any>>(object: T, path: string, split: string, value: any): T {
  const tokens = path.split(split);
  let temporary: T = {} as T;
  let temporary2: T;
  (temporary as any)[`${tokens[tokens.length - 1]}`] = value;
  for (let index = tokens.length - 2; index >= 0; index--) {
    temporary2 = {} as T;
    (temporary2 as any)[`${tokens[index]}`] = temporary;
    temporary = temporary2;
  }
  return merge(object, temporary);
}
Example #27
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 #28
Source File: theme.ts    From interface-v2 with GNU General Public License v3.0 5 votes vote down vote up
function createQuickTheme(
  custom: any,
  options?: ThemeOptions | undefined,
  ...args: any[]
) {
  return createTheme(merge(custom, options), ...args);
}
Example #29
Source File: mods-state.ts    From ow-mod-manager with MIT License 5 votes vote down vote up
modMapState = selector({
  key: 'ModMap',
  get: ({ get }) =>
    merge<ModMap, ModMap, ModMap>({}, get(remoteModMap), get(localModMap)),
})