UNPKG

2.42 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * strict-local
8 * @format
9 */
10'use strict';
11
12var _defineProperty2 = require("@babel/runtime/helpers/interopRequireDefault")(require("@babel/runtime/helpers/defineProperty"));
13
14/**
15 * A file backed cache. Values are JSON encoded on disk, so only JSON
16 * serializable values should be used.
17 */
18var RelayCompilerCache =
19/*#__PURE__*/
20function () {
21 /**
22 * @param name Human readable identifier for the cache
23 * @param cacheBreaker This should be changed in order to invalidate existing
24 * caches.
25 */
26 function RelayCompilerCache(name, cacheBreaker) {
27 (0, _defineProperty2["default"])(this, "_dir", null);
28 this._name = name;
29 this._cacheBreaker = cacheBreaker;
30 }
31
32 var _proto = RelayCompilerCache.prototype;
33
34 _proto._getFile = function _getFile(key) {
35 if (this._dir == null) {
36 // Include username in the cache dir to avoid issues with directories being
37 // owned by a different user.
38 var username = require("os").userInfo().username;
39
40 var cacheID = require("crypto").createHash('md5').update(this._cacheBreaker).update(username).digest('hex');
41
42 var dir = require("path").join(require("os").tmpdir(), "".concat(this._name, "-").concat(cacheID));
43
44 if (!require("fs").existsSync(dir)) {
45 try {
46 require("fs").mkdirSync(dir);
47 } catch (error) {
48 if (error.code !== 'EEXIST') {
49 throw error;
50 }
51 }
52 }
53
54 this._dir = dir;
55 }
56
57 return require("path").join(this._dir, key);
58 };
59
60 _proto.getOrCompute = function getOrCompute(key, compute) {
61 var _this = this;
62
63 return require("./GraphQLCompilerProfiler").run('RelayCompilerCache.getOrCompute', function () {
64 var cacheFile = _this._getFile(key);
65
66 if (require("fs").existsSync(cacheFile)) {
67 try {
68 return JSON.parse(require("fs").readFileSync(cacheFile, 'utf8'));
69 } catch (_unused) {// ignore
70 }
71 }
72
73 var value = compute();
74
75 try {
76 require("fs").writeFileSync(cacheFile, JSON.stringify(value), 'utf8');
77 } catch (_unused2) {// ignore
78 }
79
80 return value;
81 });
82 };
83
84 return RelayCompilerCache;
85}();
86
87module.exports = RelayCompilerCache;
\No newline at end of file