npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

object-rewrite

v11.0.1

Published

Rewrite Object(s) in place using plugins.

Downloads

1,554

Readme

object-rewrite

Build Status Test Coverage Dependabot Status Dependencies NPM Downloads Semantic-Release Gardener

Rewrite Object(s) in place using plugins.

This library is used for doing complex in-memory modifications of data. It allows to define use cases in a dynamic way that allows for powerful abstraction.

Install

npm i --save object-rewrite

Getting Started

import {
  injectPlugin,
  filterPlugin,
  sortPlugin,
  rewriter
} from 'object-rewrite';

const queryDataStore = (fields) => { /* ... */ };

const inject = injectPlugin({
  target: 'idNeg',
  requires: ['id'],
  fn: ({ value }) => -value.id
});
const filter = filterPlugin({
  target: '*',
  requires: ['idNeg'],
  fn: ({ value }) => [-2, -1].includes(value.idNeg)
});
const sort = sortPlugin({
  target: '*',
  requires: ['idNeg'],
  fn: ({ value }) => value.idNeg
});
const rew = rewriter({ '': [inject, filter, sort] }, ['id']);

const desiredFields = ['id'];
const rewInstance = rew.init(desiredFields, {/* init context */});

const data = queryDataStore(rewInstance.fieldsToRequest);
// data => [{ id: 0 }, { id: 1 }, { id: 2 }]

rewInstance.rewrite(data);
// data => [{ id: 2 }, { id: 1 }]

Please see the tests for more in-depth examples on how to use this library.

Plugins

There are three types of plugins INJECT, FILTER and SORT.

All plugins define:

  • target String: target field relative to the plugin path.
  • required Array: required fields relative to the plugin path. Can specify relative to root by prefixing with /. Will influence fieldsToRequest. Can be specified as function that takes initContext and expected to return array.
  • beforeFn Function: executed before any fn execution happens for plugin type
  • fn Function: result of this function is used by the plugin. Signature is fn({ key, value, parents, context, cache }).
  • onInit({ context, cache }) Function (optional): if present called once per init, used to initialize cache, if returns other than true, the plugin is disabled
  • onRewrite({ data, context, cache }) Function (optional): if present called once per rewrite, used to update cache, if returns other than true, the plugin is disabled
  • schema: Object schema structure of form { initContext: {}, rewriteContext: {}, fnInput: {}, fnOutput: {} } of what is expected to be present in corresponding context (subset)

where:

  • key: is the key for the processed entity
  • value is the value of the processed entity
  • parents are the parents of the processed entity
  • context is global as passed into the execution
  • cache = {} is locally defined per plugin
  • schema.fnInput (optional) is used to validate value before passed into fn
  • schema.fnOutput is used by the inject plugin only

Inject Plugin

Used to inject data

  • target: field that is created or overwritten, can be '*'
  • requires: See above
  • fn: return value is used for target. Relative to prefix
  • schema.fnOutput: Object schema structure of what is being injected (strict result of fn)

Filter Plugin

Used to filter arrays

  • target: array that should be filtered
  • required: See above
  • fn: target is removed iff function returns false. Similar to Array.filter(). Relative to target

Sort Plugin

Used to sort arrays

  • target: array that should be sorted
  • required: See above
  • fn: called for each object in array. Final array is sorted using the result. Relative to target
  • limit: optional limit function that takes the context object as a kwarg and is expected to return a non-negative integer or undefined. If multiple sort plugins are defined, the smallest limit is used. If the limit function returns undefined it is ignored. If set, after sorting only the first limit entries are returned.

Only one sort plugin can be specified per target.

Allows for complex sort comparisons and uses cmp-fn.js under the hood (see source code).

rewriter(pluginMap: Object, dataStoreFields: Array)

Used to combine multiple plugins. Plugins can be re-used in different rewriters. Rewriters are then used to modify input data.

Constructor takes in an object that maps absolute paths to plugins and the available dataStoreFields. Could for example re-use a plugin as

import { injectPlugin, rewriter } from 'object-rewrite';

const plugin = injectPlugin(/* ... */);

rewriter({
  '': [plugin],
  nodes: [plugin]
}, [/* data store fields */]);

allowedFields: Array

Fields that are allowed to be requested.

init(fields: Array)

Initialize the rewriter for a specific set of fields.

fieldsToRequest

Exposes fields which should be requested from data store. Dynamically computed fields are excluded since they would not be present in the data store.

rewrite(data: Object/Array, context: Object = {})

Pass in object that should be rewritten. The context allows for additional data to be made available for all plugins.

Notes

Dynamic Keys

Under the hood this library uses object-scan. Please refer to the docs for what key pattern are supported.

Execution Order

Plugins are executed in the order INJECT, FILTER and then SORT.

Plugins within the same type are evaluated bottom-up. While this is less performant, it allows plugins to rely on previous executed plugins of the same type.

Plugins of the same type that operate on the same target are executed in order.

Async

To apply an async rewrite, please use

rewInstance.rewriteAsync(data);

Only plugin that can use an async fn in an Inject plugin. An async result is evaluated after all inject plugins have run, and hence can only be used in filter and sort plugins, but not in other inject plugins.