Lib: Migrations
A FoundryVTT module library that makes it easy to run and track migrations.
Overview
Lib: Migrations runs data migrations for a module when the shape of its stored data changes. You register your module, define its migrations, and call the run method yourself - the library never runs them on your behalf. It keeps track of which migrations have already succeeded so they are not applied twice.
This is a library. Install it alongside a module that requires it; on its own it does nothing.
Features
- Easily define migrations with a comprehensive API
- Fully typed library included in repository for Typescript projects
Usage
To use this in your own module, you can do any of the following:
- Use the
migrations.setuphook (which fires based on Foundry'ssetuphook) and register your module and migrations on the provided instance ofmigrations - Use the
migrations.readyhook (which fires based on Foundry'sreadyhook) to run your migrations - Use the
window.migrations(accessible as justmigrationsin console and code) and register, add migrations, and run them wherever it makes sense.
Everything will be ready to migrate when the Foundry ready hook is complete. However, you can run them whenever you want using the global migrations instance.
You cannot register your module or any migrations in the Foundry init hook.
General Guidelines
- You MUST call the run migrations method yourself. This library makes no assumption as to when it makes sense for your module's migrations to execute.
- It is safe to always run the migrations each time, as they will not be re-ran if they succeeded.
- Each migration should be repeatable in case the user accidentally loses the data on which migrations were run. Generally, this just boils down to doing some if/else checks before running a migration.
- If a migration unexpectedly fails, it will not be added to the list of migrations that ran. This means the next time the migrations would run, it will attempt to run that migration again.
- If a migration fails, all subsequent migrations (based on date) will not run. This is to allow for certain assumptions in the data you're working with based on previous migrations.
Hooks
Lib: DFreds Migrations provides a few hooks.
migrations.setup- This is called once on Foundry'ssetuphook. It should be used to register your module and migrations using the provided instance ofmigrations.migrations.ready- This is called once on Foundry'sreadyhook. At this point, migrations can be run (you must call this yourself).
API Methods
Currently, these are the supported API methods: https://github.com/DFreds/lib-dfreds-migrations/blob/main/types/migrations/index.d.ts
Sample
A sample setup can be found here: https://github.com/DFreds/lib-dfreds-migrations/blob/main/src/ts/sample.ts.
For a more real-world example, you can view these two commits in the DFreds Convenient Effects repository that change to using the library from a built-in migration solution.