Skip to content

Commit

Permalink
Add support for async migrations (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante committed Apr 5, 2023
1 parent 35941c5 commit e058f9e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
5 changes: 3 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export interface Options {
/*
Handler signature for when an extension updates.
*/
export type Migration<UserOptions extends Options> = (savedOptions: UserOptions, defaults: UserOptions) => void;
export type Migration<UserOptions extends Options> = (savedOptions: UserOptions, defaults: UserOptions) => Promise<void>;

class OptionsSync<UserOptions extends Options> {
public static migrations = {
Expand Down Expand Up @@ -235,7 +235,8 @@ class OptionsSync<UserOptions extends Options> {
this._log('log', 'Found these stored options', {...options});
this._log('info', 'Will run', migrations.length, migrations.length === 1 ? 'migration' : ' migrations');
for (const migrate of migrations) {
migrate(options, this.defaults);
// eslint-disable-next-line no-await-in-loop -- Must be done in order
await migrate(options, this.defaults);
}

// Only save to storage if there were any changes
Expand Down
8 changes: 7 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,12 @@ test.serial('migrations alter the stored options', async t => {

const storage = new OptionsSync({
migrations: [
async savedOptions => {
await new Promise(resolve => {
setTimeout(resolve, 100);
});
savedOptions.size += 10;
},
savedOptions => {
if (typeof savedOptions.size !== 'undefined') {
savedOptions.minSize = savedOptions.size;
Expand All @@ -175,7 +181,7 @@ test.serial('migrations alter the stored options', async t => {
t.is(chrome.storage.sync.set.callCount, 1);
t.deepEqual(chrome.storage.sync.set.firstCall.args[0], {
options: compressOptions({
minSize: 30,
minSize: 40,
}),
});
});
Expand Down

0 comments on commit e058f9e

Please sign in to comment.