Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@
"markdown-to-jsx": "^7.4.7",
"prop-types": "^15.8.1",
"recoil": "^0.7.7",
"regenerator-runtime": "^0.14.1"
"regenerator-runtime": "^0.14.1",
"uuid": "^11.1.1"
},
"dependenciesNotes": {},
"peerDependencies": {
Expand Down
16 changes: 14 additions & 2 deletions src/components/common/help/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ import Divider from "components/common/modal/divider";
import except from "lib/common/object/except";
import useHttp from "lib/hooks/use-http";
import useTranslate from "lib/hooks/use-translate";
import {activeState, baseState, errorsState, orderState} from "lib/recoil";
import {
activeState,
baseState,
errorsState,
orderState,
requestIDsState
} from "lib/recoil";
import style from "./style.scss";

function Modal({show, setShow}) {
Expand All @@ -25,6 +31,7 @@ function Modal({show, setShow}) {
const base = useRecoilValue(baseState);
const errors = useRecoilValue(errorsState);
const order = useRecoilValue(orderState);
const requestIDs = useRecoilValue(requestIDsState);
const submitting = useRef(false);

if(!show) { return null; }
Expand All @@ -47,7 +54,12 @@ function Modal({show, setShow}) {
const params = {
errors,
message,
state: {active, base, order: {}},
requestIDs,
state: {
active,
base,
order: {}
},
widget: {source: SOURCE, version: VERSION}
};

Expand Down
34 changes: 28 additions & 6 deletions src/components/container/hooks/use-props.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {useEffect} from "react";
import {useEffect, useState} from "react";
import {useSetRecoilState} from "recoil";
import Cache from "lib/cache";
import slice from "lib/common/object/slice";
Expand All @@ -7,27 +7,34 @@ import Http from "lib/http";
import I18n from "lib/i18n";
import Listener from "lib/listener";
import {
appendRequestIDState,
baseState,
cacheState,
graphqlState,
httpState,
i18nState,
listenerState,
localeState,
optionsState
optionsState,
requestIDState
} from "lib/recoil";
import {chainRequestID, generateWidgetID} from "lib/request-id";

const EMPTY_OPTIONS = {};

export default function useProps(props) {
const setBase = useSetRecoilState(baseState);
const setCache = useSetRecoilState(cacheState);
const setGraphql = useSetRecoilState(graphqlState);
const appendRequestID = useSetRecoilState(appendRequestIDState);
const setHttp = useSetRecoilState(httpState);
const setRequestID = useSetRecoilState(requestIDState);
const setI18n = useSetRecoilState(i18nState);
const setListener = useSetRecoilState(listenerState);
const setLocale = useSetRecoilState(localeState);
const setOptions = useSetRecoilState(optionsState);
const [fallbackListener] = useState(() => new Listener());
const listener = props.listener || fallbackListener;
const {
assessmentID,
benchmarkID,
Expand Down Expand Up @@ -60,16 +67,31 @@ export default function useProps(props) {
}, [props.cache]);

useEffect(() => {
setHttp(props.http || new Http(slice(options, ["authKey", "host", "version"])));
}, [props.http]);
const http = props.http || new Http(slice(options, ["authKey", "host", "version"]));
http.listener = listener;
setHttp(http);
}, [props.http, listener]);

useEffect(() => {
const widgetID = options.requestID || generateWidgetID();
setRequestID(widgetID);

return listener.on("Http.request", (request) => {
const requestID = chainRequestID(widgetID);
// NOTE: Defer updating state so it happens after the render
queueMicrotask(() => appendRequestID(requestID));

request.options.headers = {...request.options.headers, "X-Request-Id": requestID};
});
}, [listener]);

useEffect(() => {
setI18n(props.i18n || new I18n());
}, [props.i18n]);

useEffect(() => {
setListener(props.listener || new Listener());
}, [props.listener]);
setListener(listener);
}, [listener]);

useEffect(() => {
const base = {};
Expand Down
8 changes: 7 additions & 1 deletion src/lib/http/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import withRetry from "./retry";
import toQueryString from "../common/object/to-query-string";
import Listener from "../listener";

const formatArgs = ({method, options, params}) => {
if(typeof options === "object") { return {method, ...options}; }
Expand All @@ -21,6 +22,7 @@ export default class Http {
this.authKey = authKey;
this.autoRetry = autoRetry || false;
this.host = host || "https://api.traitify.com";
this.listener = new Listener();
this.retryOptions = retryOptions || {};
this.version = version || "v1";
}
Expand Down Expand Up @@ -54,8 +56,12 @@ export default class Http {
options.body = JSON.stringify(params);
}

// NOTE: Allows listeners to mutate the request object
const request = {options, url};
this.listener.trigger("Http.request", request);

const retryEnabled = this.autoRetry || retryOptions != null;
const fetchFn = () => this.fetch(url, options);
const fetchFn = () => this.fetch(request.url, request.options);
const responsePromise = retryEnabled
? withRetry({fetch: fetchFn, method, options: {...this.retryOptions, ...retryOptions}})
: fetchFn();
Expand Down
8 changes: 8 additions & 0 deletions src/lib/recoil/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export const localeState = atom({
});
export const optionsState = atom({default: null, key: "options"});
export const orderIDState = atom({default: null, key: "order-id"});
export const requestIDState = atom({default: null, key: "request-id"});
export const requestIDsState = atom({default: [], key: "request-ids"});
export const packageIDState = atom({default: null, key: "package-id"});
export const profileIDState = atom({default: null, key: "profile-id"});
export const skipDismissedState = atom({default: false, key: "skip-dismissed"});
Expand All @@ -35,6 +37,12 @@ export const appendErrorState = selector({
key: "append-error-state"
});

export const appendRequestIDState = selector({
get: ({get}) => get(requestIDsState),
set: ({get, set}, newValue) => set(requestIDsState, [...get(requestIDsState), newValue]),
key: "append-request-id-state"
});

// NOTE: Breaking up state prevents over-triggering selectors
export const activeIDState = selector({
get: ({get}) => {
Expand Down
4 changes: 4 additions & 0 deletions src/lib/request-id.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import {v7 as uuid} from "uuid";

export const chainRequestID = (widgetID) => `${widgetID}.${uuid().slice(-6)}`;
export const generateWidgetID = () => `widget-${uuid()}`;
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ exports[`Survey.Cognitive submit submits query 1`] = `
"Accept": "application/json",
"Authorization": "Basic dW5kZWZpbmVkOng=",
"Content-Type": "application/json",
"X-Request-Id": "widget-test.aaaaaa",
},
"method": "POST",
},
Expand All @@ -365,6 +366,7 @@ exports[`Survey.Cognitive submit submits query with fallbacks 1`] = `
"Accept": "application/json",
"Authorization": "Basic dW5kZWZpbmVkOng=",
"Content-Type": "application/json",
"X-Request-Id": "widget-test.aaaaaa",
},
"method": "POST",
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ exports[`Survey.Generic submit submits query 1`] = `
"Accept": "application/json",
"Authorization": "Basic dW5kZWZpbmVkOng=",
"Content-Type": "application/json",
"X-Request-Id": "widget-test.aaaaaa",
},
"method": "POST",
},
Expand Down
41 changes: 41 additions & 0 deletions test/lib/http.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,47 @@ describe("Http", () => {
);
});

it("triggers request listeners with the built request", () => {
const onRequest = jest.fn().mockName("onRequest");
http.listener.on("Http.request", onRequest);
http.request({method: "GET", path: "/profiles"});

expect(onRequest).toHaveBeenCalledWith({
options: expect.objectContaining({method: "GET"}),
url: "https://api.traitify.com/v1/profiles"
});
});

it("fetches with mutations made by request listeners", () => {
http.listener.on("Http.request", (request) => { request.options.headers["X-Request-Id"] = "widget-abc.aaaaaa"; });
http.request({method: "GET", path: "/profiles"});

expect(lastHeaders()["X-Request-Id"]).toBe("widget-abc.aaaaaa");
});

it("applies multiple request listeners", () => {
http.listener.on("Http.request", (request) => { request.options.headers["X-A"] = "a"; });
http.listener.on("Http.request", (request) => { request.options.headers["X-B"] = "b"; });
http.request({method: "GET", path: "/profiles"});

expect(lastHeaders()).toEqual(expect.objectContaining({"X-A": "a", "X-B": "b"}));
});

it("stops invoking a listener after it is unregistered", () => {
const onRequest = jest.fn().mockName("onRequest");
const off = http.listener.on("Http.request", onRequest);
off();
http.request({method: "GET", path: "/profiles"});

expect(onRequest).not.toHaveBeenCalled();
});

it("fetches unchanged when no request listeners are registered", () => {
http.request({method: "GET", path: "/profiles"});

expect(lastHeaders()).not.toHaveProperty("X-Request-Id");
});

it("passes query params", () => {
http.request({method: "GET", path: "/profiles", params: {locale_key: "en-us"}});

Expand Down
23 changes: 23 additions & 0 deletions test/lib/request-id.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const {chainRequestID, generateWidgetID} = jest.requireActual("lib/request-id");

describe("request-id", () => {
describe("generateWidgetID", () => {
it("prefixes the id with widget-", () => {
expect(generateWidgetID()).toMatch(/^widget-/);
});

it("generates a unique id each call", () => {
expect(generateWidgetID()).not.toBe(generateWidgetID());
});
});

describe("chainRequestID", () => {
it("appends a 6-char hex code to the widget id", () => {
expect(chainRequestID("widget-abc")).toMatch(/^widget-abc\.[0-9a-f]{6}$/);
});

it("generates a unique code each call", () => {
expect(chainRequestID("widget-abc")).not.toBe(chainRequestID("widget-abc"));
});
});
});
4 changes: 4 additions & 0 deletions test/support/setup/container.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
jest.mock("lib/common/load-font");
jest.mock("lib/request-id", () => ({
chainRequestID: (widgetID) => `${widgetID}.aaaaaa`,
generateWidgetID: () => "widget-test"
}));

afterEach(() => { jest.clearAllTimers(); });