@graphql-hive/core
Version:
153 lines (152 loc) • 4.73 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHash = createHash;
exports.memo = memo;
exports.isAsyncIterable = isAsyncIterable;
exports.cache = cache;
exports.cacheDocumentKey = cacheDocumentKey;
exports.measureDuration = measureDuration;
exports.addProperty = addProperty;
exports.isHiveClient = isHiveClient;
exports.logIf = logIf;
exports.joinUrl = joinUrl;
exports.createHiveLogger = createHiveLogger;
const fetch_1 = require("@whatwg-node/fetch");
const client_js_1 = require("./client.js");
async function digest(algo, output, data) {
const buffer = await fetch_1.crypto.subtle.digest(algo, new fetch_1.TextEncoder().encode(data));
if (output === 'hex') {
return arrayBufferToHEX(buffer);
}
return arrayBufferToBase64(buffer);
}
function arrayBufferToHEX(buffer) {
return Array.prototype.map
.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2))
.join('');
}
function arrayBufferToBase64(buffer) {
return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
}
function createHash(algo) {
let str = '';
return {
update(data) {
str += data;
return this;
},
async digest(output) {
return digest(algo, output, str);
},
};
}
function memo(fn, cacheKeyFn) {
let memoizedResult = null;
let memoizedKey = null;
return (arg) => {
const currentKey = cacheKeyFn(arg);
if (memoizedKey === currentKey) {
return memoizedResult;
}
memoizedKey = currentKey;
memoizedResult = fn(arg);
return memoizedResult;
};
}
function isAsyncIterable(value) {
return (value === null || value === void 0 ? void 0 : value[Symbol.asyncIterator]) != null;
}
function cache(fn, cacheKeyFn, cacheMap) {
return async (arg, arg2) => {
const key = await cacheKeyFn(arg, arg2);
const cachedValue = await cacheMap.get(key);
if (cachedValue !== null && typeof cachedValue !== 'undefined') {
return {
key,
value: cachedValue,
cacheHit: true,
};
}
const value = fn(arg, arg2);
cacheMap.set(key, value);
return {
key,
value,
cacheHit: false,
};
};
}
async function cacheDocumentKey(doc, variables) {
const hasher = createHash('SHA-1').update(JSON.stringify(doc));
if (variables) {
hasher.update(JSON.stringify(variables, (_, value) => {
if ((value && typeof value === 'object' && Object.keys(value).length) ||
(Array.isArray(value) && value.length)) {
return value;
}
return '';
}));
}
return hasher.digest('hex');
}
const HR_TO_NS = 1e9;
const NS_TO_MS = 1e6;
function deltaFrom(startedAt) {
const endedAt = performance.now();
const ns = Math.round(((endedAt - startedAt) * HR_TO_NS) / 1000);
return {
ns,
get ms() {
return ns / NS_TO_MS;
},
};
}
function measureDuration() {
const startAt = performance.now();
return function end() {
return deltaFrom(startAt).ns;
};
}
function addProperty(key, value, obj) {
if (value === null || typeof value === 'undefined') {
return obj;
}
return Object.assign(Object.assign({}, obj), { [key]: value });
}
function isHiveClient(clientOrOptions) {
return client_js_1.hiveClientSymbol in clientOrOptions;
}
function logIf(condition, message, logFn) {
if (condition) {
logFn(message);
}
}
function joinUrl(url, subdirectory) {
const normalizedUrl = url.endsWith('/') ? url.slice(0, -1) : url;
const normalizedSubdirectory = subdirectory.startsWith('/')
? subdirectory.slice(1)
: subdirectory;
return normalizedUrl + '/' + normalizedSubdirectory;
}
const hiveSymbol = Symbol('hive-logger');
function createHiveLogger(baseLogger, prefix) {
const context = Object.assign({ path: '', logger: baseLogger }, baseLogger === null || baseLogger === void 0 ? void 0 : baseLogger[hiveSymbol]);
context.path = context.path + prefix;
const { logger, path } = context;
return {
[hiveSymbol]: context,
info: (message) => {
logger.info(`${path} ${message}`);
},
error: (error, ...data) => {
if (error.stack) {
for (const stack of error.stack.split('\n')) {
logger.error(`${path} ${stack}`);
}
}
else {
logger.error(`${path} ${String(error)}`, ...data);
}
},
};
}
;