Make FileStore fully generic

Reviewed By: rafeca

Differential Revision: D7714699

fbshipit-source-id: 7886f99015a88fe4c92c104627aff995ea3dba42
This commit is contained in:
Miguel Jimenez Esun 2018-04-23 07:51:25 -07:00 committed by Facebook Github Bot
parent bce317701b
commit e32c71dc36
3 changed files with 48 additions and 18 deletions

View File

@ -16,5 +16,8 @@
"metro-core": "0.34.0",
"mkdirp": "^0.5.1",
"rimraf": "^2.5.4"
},
"devDependencies": {
"metro-memory-fs": "0.34.0"
}
}

View File

@ -21,9 +21,6 @@ export type Options = {|
root: string,
|};
const JOINER_DATA = '\0\0';
const JOINER_LIST = '\0';
class FileStore {
_root: string;
@ -34,14 +31,7 @@ class FileStore {
get(key: Buffer): ?TransformedCode {
try {
const data = fs.readFileSync(this._getFilePath(key), 'utf8');
const [code, dependencies, map] = data.split(JOINER_DATA);
return {
code,
dependencies: dependencies ? dependencies.split(JOINER_LIST) : [],
map: JSON.parse(map),
};
return JSON.parse(fs.readFileSync(this._getFilePath(key), 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') {
return null;
@ -52,13 +42,7 @@ class FileStore {
}
set(key: Buffer, value: TransformedCode): void {
const data = [
value.code,
value.dependencies.join(JOINER_LIST),
JSON.stringify(value.map),
].join(JOINER_DATA);
fs.writeFileSync(this._getFilePath(key), data);
fs.writeFileSync(this._getFilePath(key), JSON.stringify(value));
}
clear() {

View File

@ -0,0 +1,43 @@
/**
* Copyright (c) 2018-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+javascript_foundation
* @format
*/
'use strict';
describe('FileStore', () => {
let FileStore;
let fs;
beforeEach(() => {
jest
.resetModules()
.resetAllMocks()
.useFakeTimers()
.mock('fs', () => new (require('metro-memory-fs'))());
FileStore = require('../FileStore');
fs = require('fs');
jest.spyOn(fs, 'unlinkSync');
});
it('sets and writes into the cache', () => {
const fileStore = new FileStore({root: '/root'});
const cache = new Buffer([0xfa, 0xce, 0xb0, 0x0c]);
fileStore.set(cache, {foo: 42});
expect(fileStore.get(cache)).toEqual({foo: 42});
});
it('returns null when reading a non-existing file', () => {
const fileStore = new FileStore({root: '/root'});
const cache = new Buffer([0xfa, 0xce, 0xb0, 0x0c]);
expect(fileStore.get(cache)).toEqual(null);
});
});