UNPKG

2.73 kBJavaScriptView Raw
1import { combine, dateAdd, hOP, isFunc, objectDefinedNotNull } from "@pnp/core";
2import { JSONParse } from "@pnp/queryable";
3import { extractWebUrl } from "../utils/extract-web-url.js";
4import { SPQueryable } from "../spqueryable.js";
5import { spPost } from "../operations.js";
6import { BatchNever } from "../batching.js";
7function clearExpired(digest) {
8 const now = new Date();
9 return !objectDefinedNotNull(digest) || (now > digest.expiration) ? null : digest;
10}
11// allows for the caching of digests across all calls which each have their own IDigestInfo wrapper.
12const digests = new Map();
13export function RequestDigest(hook) {
14 return (instance) => {
15 instance.on.pre(async function (url, init, result) {
16 // add the request to the auth moment of the timeline
17 this.on.auth(async (url, init) => {
18 // eslint-disable-next-line max-len
19 if (/get/i.test(init.method) || (init.headers && (hOP(init.headers, "X-RequestDigest") || hOP(init.headers, "Authorization") || hOP(init.headers, "X-PnPjs-NoDigest")))) {
20 return [url, init];
21 }
22 const urlAsString = url.toString();
23 const webUrl = extractWebUrl(urlAsString);
24 // do we have one in the cache that is still valid
25 // from #2186 we need to always ensure the digest we get isn't expired
26 let digest = clearExpired(digests.get(webUrl));
27 if (!objectDefinedNotNull(digest) && isFunc(hook)) {
28 digest = clearExpired(hook(urlAsString, init));
29 }
30 if (!objectDefinedNotNull(digest)) {
31 digest = await spPost(SPQueryable([this, combine(webUrl, "_api/contextinfo")]).using(JSONParse(), BatchNever()), {
32 headers: {
33 "X-PnPjs-NoDigest": "1",
34 },
35 }).then(p => ({
36 expiration: dateAdd(new Date(), "second", p.FormDigestTimeoutSeconds),
37 value: p.FormDigestValue,
38 }));
39 }
40 if (objectDefinedNotNull(digest)) {
41 // if we got a digest, set it in the headers
42 init.headers = {
43 "X-RequestDigest": digest.value,
44 ...init.headers,
45 };
46 // and cache it for future requests
47 digests.set(webUrl, digest);
48 }
49 return [url, init];
50 });
51 return [url, init, result];
52 });
53 return instance;
54 };
55}
56//# sourceMappingURL=request-digest.js.map
\No newline at end of file