Skip to content

Instantly share code, notes, and snippets.

@joepie91
Created April 24, 2021 20:53
Show Gist options
  • Save joepie91/187c0abaae0283d7f8565792f186b629 to your computer and use it in GitHub Desktop.
Save joepie91/187c0abaae0283d7f8565792f186b629 to your computer and use it in GitHub Desktop.
// FETCH response sent as result of FETCH request
var msg = this._curReq.fetchCache[info.num],
keys = Object.keys(info.text),
keyslen = keys.length,
toget, msgEmitter, j;
if (msg === undefined) {
// simple case -- no bodies were streamed
toget = this._curReq.fetching.slice(0);
if (toget.length === 0)
return;
msgEmitter = new EventEmitter();
attrs = {};
this._curReq.bodyEmitter.emit('message', msgEmitter, info.num);
} else {
toget = msg.toget;
msgEmitter = msg.msgEmitter;
attrs = msg.attrs;
}
i = toget.length;
if (i === 0) {
if (msg && !msg.ended) {
msg.ended = true;
process.nextTick(function() {
msgEmitter.emit('end');
});
}
return;
}
if (keyslen > 0) {
while (--i >= 0) {
j = keyslen;
while (--j >= 0) {
if (keys[j].toUpperCase() === toget[i]) {
if (!RE_BODYPART.test(toget[i])) {
if (toget[i] === 'X-GM-LABELS') {
var labels = info.text[keys[j]];
for (var k = 0, lenk = labels.length; k < lenk; ++k)
labels[k] = (''+labels[k]).replace(RE_ESCAPE, '\\');
}
key = FETCH_ATTR_MAP[toget[i]];
if (!key)
key = toget[i].toLowerCase();
attrs[key] = info.text[keys[j]];
}
toget.splice(i, 1);
break;
}
}
}
}
if (toget.length === 0) {
if (msg)
msg.ended = true;
process.nextTick(function() {
msgEmitter.emit('attributes', attrs);
msgEmitter.emit('end');
});
} else if (msg === undefined) {
this._curReq.fetchCache[info.num] = {
msgEmitter: msgEmitter,
toget: toget,
attrs: attrs,
ended: false
};
}
if (keysToFetch.length > 0) {
let caseMappedPayload = mapObject(payload, (key, value) => {
return [ key.toUpperCase(), value ];
});
let [ existingKeys, missingKeys ] = splitFilter(keysToFetch, (key) => caseMappedPayload[key] != null);
let relevantKeys = existingKeys.filter((key) => RE_BODYPART.test(key) === false);
let newAttributes = syncpipe(caseMappedPayload, [
(_) => pickObject(_, relevantKeys),
(_) => mapObject(_, (key, value) => {
return [
/* key */ mapIncomingAttributeKey(key),
/* value */ (key === 'X-GM-LABELS')
// TODO: Why is this special case needed?
? value.map((label) => String(label).replace(RE_ESCAPE, '\\'))
: value
];
})
]);
// console.log({ existingKeys, missingKeys, relevantKeys, newAttributes, caseMappedPayload });
Object.assign(attributes, newAttributes);
keysToFetch = missingKeys;
let isDone = (missingKeys.length === 0);
if (isDone === true) {
endHandled = true;
// FIXME: Why nextTick?
process.nextTick(function() {
emitter.emit("attributes", attributes);
emitter.emit("end");
});
}
} else {
if (endHandled === false) {
endHandled = true;
// FIXME: Why nextTick?
process.nextTick(function() {
emitter.emit("end");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment