Skip to content

simonwep/yuppee

Repository files navigation


Type-Safe migration utility to migrate from one data-schema to another.


License MIT No dependencies Support me version Buy me a coffee Build Status gzip size brotli size

Summary

This is a small package to facilitate the transition from one data-structure to another. It may be useful if you have settings or very little state that is stored as a single JSON-Object that needs to be migrated to another schema at some point.

Usage

Install it using your preferred package manager (taking npm as example):

npm install yuppee
import { createMigration, createMigrator } from 'yuppee';

// All possible versions your clients may have.
type StateV1 = { version: 1, name?: string };
type StateV2 = { version: 2, names: string[] };
type StateV3 = { version: 3, data: { names: string[] } };

// This is the type that should be used throughout your app.
// It's an alias to the latest version and can be re-mapped on every update.
type State = StateV3;

const migrate = createMigrator<State, StateV1 | StateV2>({
    init: () => ({ name: 'baz' }),
    migrations: [
        createMigration<StateV1, StateV2>({
            from: 1,
            to: 2,
            migrate: (state) => ({
                names: state.name ? [state.name] : []
            })
        }),
        createMigration<StateV2, StateV3>({
            from: 2,
            to: 3,
            migrate: (state) => ({
                data: { names: state.names }
            })
        })
    ]
});

/* Logs { version: 3, data: { names: ['baz'] } } */
console.log(migrate());

/* Logs { version: 3, data: { names: ['foo'] } } */
console.log(migrate({ version: 1, name: 'foo' }));

/* Logs { version: 3, data: { names: ['bar', 'bam'] } } */
console.log(migrate({ version: 2, names: ['bar', 'bam'] }));

About

⚙️ Type-safe migration library to migrate data from one schema to another.

Topics

Resources

License

Stars

Watchers

Forks