Skip to content

Commit

Permalink
Feature: Add locking via .withLock
Browse files Browse the repository at this point in the history
  • Loading branch information
nick spragg committed Jan 18, 2017
1 parent 6ad1c3c commit 1547671
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@
},
"dependencies": {
"bluebird": "^3.4.7",
"fs-ext": "^0.5.0",
"fs-extra": "^2.0.0",
"lockfile": "^1.0.3",
"minimatch": "^3.0.3"
}
}
12 changes: 12 additions & 0 deletions src/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import fs from 'fs';
import path from 'path';
import fileGlob from 'minimatch';

import lock from './lock';

const fsp = Promise.promisifyAll(fs);

function joinWith(dir) {
Expand Down Expand Up @@ -156,6 +158,16 @@ class File {
delete() {
return fsp.unlinkAsync(this._pathname);
}

withLock(fn) {
return lock.lockAsync(this._pathname)
.then(() => {
fn();
})
.finally(() => {
return lock.unlockAsync(this._pathname);
});
}
}

module.exports.create = (filename) => {
Expand Down
4 changes: 4 additions & 0 deletions src/lock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import lockfile from 'lockfile';
import Promise from 'bluebird';

module.exports = Promise.promisifyAll(lockfile);
24 changes: 24 additions & 0 deletions test/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import path from 'path';
import File from '../lib/file';
import moment from 'moment';
import sinon from 'sinon';
import Promise from 'bluebird';

import lockfile from '../lib/lock';

const sandbox = sinon.sandbox.create();

Expand Down Expand Up @@ -525,4 +528,25 @@ describe('File', () => {
assert.equal(file.getName(), getFixturePath('dates/a.txt'));
});
});

describe('.withLock', () => {
beforeEach(() => {
sandbox.stub(lockfile, 'lockAsync').returns(Promise.resolve());
sandbox.stub(lockfile, 'unlockAsync').returns(Promise.resolve());
});

afterEach(() => {
sandbox.restore();
});

it('executes a given function whilst managing a file lock', () => {
const fn = sinon.spy();
const file = File.create('justFiles/a.json');

file.withLock(fn)
.then(() => {
sinon.assert.callOrder(lockfile.lockAsync, fn, lockfile.unlockAsync);
});
});
});
});

0 comments on commit 1547671

Please sign in to comment.