Skip to content

feat: Add support for setting additional headers and strictApi #74

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
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
8 changes: 7 additions & 1 deletion doc/api_reference/session.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ Construct Session instance with API credentials.
:param Array [options.serverInformationValues=[]]: Optional list of server information values to retrieve.
:param Object [options.eventHubOptions={}]: Options to configure event hub with.
:param string [options.clientToken=null]: Client identifier included in update events caused by operations performed by this session.
:param Object [options.headers]: Additional headers to send with the request

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be options.additionalHeaders?

:param Object [options.strictApi]: Turn on strict API mode

Function ``call``
=================
Expand All @@ -45,8 +47,12 @@ ServerError


:param Array operations: API operations.
:param Object [options]: options
:param Object [options.abortController]: - Deprecated in favour of options.signal
:param Object [options.signal]: - Abort signal user for aborting requests prematurely
:param Object [options.headers]: - Additional headers to send with the request


:return Promise: Promise which will be resolved with an array of decoded responses.

Function ``getSchema``
======================
Expand Down
40 changes: 38 additions & 2 deletions source/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ export interface SessionOptions {
eventHubOptions?: EventHubOptions;
clientToken?: string;
apiEndpoint?: string;
additionalHeaders?: Data;
strictApi?: boolean;
}

export interface CreateComponentOptions {
Expand Down Expand Up @@ -95,11 +97,13 @@ export interface ResponseError {

export interface MutatationOptions {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MutatationOptions ? ;)

pushToken?: string;
additionalHeaders?: Data;
}

export interface QueryOptions {
abortController?: AbortController;
signal?: AbortSignal;
additionalHeaders?: Data;
}

export interface CallOptions extends MutatationOptions, QueryOptions {}
Expand All @@ -121,6 +125,7 @@ export class Session {
serverInformation?: Data;
schemas?: Data;
serverVersion?: string;
additionalHeaders: Data;

/**
* Construct Session instance with API credentials.
Expand All @@ -134,6 +139,8 @@ export class Session {
* @param {Object} [options.eventHubOptions={}] - Options to configure event hub with.
* @param {string} [options.clientToken] - Client token for update events.
* @param {string} [options.apiEndpoint=/api] - API endpoint.
* @param {object} [options.headers] - Additional headers to send with the request
* @param {object} [options.strictApi] - Turn on strict API mode
*
* @constructs Session
*/
Expand All @@ -147,6 +154,8 @@ export class Session {
eventHubOptions = {},
clientToken,
apiEndpoint = "/api",
additionalHeaders = {},
strictApi = false,
}: SessionOptions = {}
) {
if (!serverUrl || !apiUser || !apiKey) {
Expand Down Expand Up @@ -188,6 +197,21 @@ export class Session {
*/
this.apiEndpoint = apiEndpoint;

/**
* allows setting additional headers to be sent with each request
* @memberof Session
* @instance
* @type {Data}
*/
this.additionalHeaders = additionalHeaders;

if (strictApi) {
this.additionalHeaders = {
...additionalHeaders,
"ftrack-strict-api": "true",
};
}

/**
* session event hub
* @memberof Session
Expand Down Expand Up @@ -486,11 +510,17 @@ export class Session {
* @param {AbortController} options.abortController - Abort controller, deprecated in favor of options.signal
* @param {AbortSignal} options.signal - Abort signal
* @param {string} options.pushToken - push token to associate with the request
* @param {object} options.headers - Additional headers to send with the request
*
*/
call(
operations: operation.Operation[],
{ abortController, pushToken, signal }: CallOptions = {}
{
abortController,
pushToken,
signal,
additionalHeaders = {},
}: CallOptions = {}
): Promise<Response<Data>[]> {
const url = `${this.serverUrl}${this.apiEndpoint}`;

Expand All @@ -516,6 +546,8 @@ export class Session {
"ftrack-user": this.apiUser,
"ftrack-Clienttoken": this.clientToken,
"ftrack-pushtoken": pushToken,
...this.additionalHeaders,
...additionalHeaders,
} as HeadersInit,
body: this.encodeOperations(operations),
signal: abortController ? abortController.signal : signal,
Expand Down Expand Up @@ -701,12 +733,12 @@ export class Session {
* @param {object} options
* @param {object} options.abortController - Deprecated in favour of options.signal
* @param {object} options.signal - Abort signal user for aborting requests prematurely
* @param {object} options.headers - Additional headers to send with the request
* @return {Promise} Promise which will be resolved with an object
* containing action, data and metadata
*/
query(expression: string, options: QueryOptions = {}) {
logger.debug("Query", expression);

const queryOperation = operation.query(expression);
let request = this.call([queryOperation], options).then((responses) => {
const response = responses[0];
Expand All @@ -728,6 +760,7 @@ export class Session {
* @param {object} additionalOptions
* @param {object} options.abortController - Deprecated in favour of options.signal
* @param {object} options.signal - Abort signal user for aborting requests prematurely
* @param {object} options.headers - Additional headers to send with the request
* @return {Promise} Promise which will be resolved with an object
* containing data and metadata
*/
Expand Down Expand Up @@ -771,6 +804,7 @@ export class Session {
* @param {Object} data data which should be used to populate attributes on the entity.
* @param {Object} options
* @param {string} options.pushToken - push token to associate with the request
* @param {object} options.headers - Additional headers to send with the request
* @return {Promise} Promise which will be resolved with the response.
*/
create(entityType: string, data: Data, { pushToken }: CallOptions = {}) {
Expand All @@ -794,6 +828,7 @@ export class Session {
* @param {Object} data
* @param {Object} options
* @param {string} options.pushToken - push token to associate with the request
* @param {object} options.headers - Additional headers to send with the request
* @return {Promise} Promise resolved with the response.
*/
update(
Expand Down Expand Up @@ -821,6 +856,7 @@ export class Session {
* @param {Array} keys Identifying keys, typically [<entity id>]
* @param {Object} options
* @param {string} options.pushToken - push token to associate with the request
* @param {object} options.headers - Additional headers to send with the request
* @return {Promise} Promise resolved with the response.
*/
delete(type: string, keys: string[], { pushToken }: MutatationOptions = {}) {
Expand Down
15 changes: 13 additions & 2 deletions test/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import fs from "fs/promises";
import querySchemas from "./fixtures/query_schemas.json";
import queryServerInformation from "./fixtures/query_server_information.json";
import getUploadMetadata from "./fixtures/get_upload_metadata.json";
import exampleQuery from "./fixtures/query_select_name_from_task_limit_1.json";
import { setupServer } from "msw/node";

function authenticate(req) {
// allow returning invalid authentication by setting ftrack-api-key to "INVALID_API_KEY"
Expand All @@ -21,7 +23,16 @@ function pick(object, keys) {
return obj;
}, {});
}
const handlers = [

export function getInitialSessionQuery() {
return [queryServerInformation, querySchemas];
}

export function getExampleQuery() {
return [exampleQuery];
}

export const handlers = [
rest.post("http://ftrack.test/api", async (req, res, ctx) => {
if (!authenticate(req)) {
return res(
Expand Down Expand Up @@ -111,4 +122,4 @@ const handlers = [
}),
];

export { handlers };
export const server = setupServer(...handlers);
67 changes: 67 additions & 0 deletions test/session.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ import { Session } from "../source/session";
import * as operation from "../source/operation";
import { expect } from "chai";

import { getExampleQuery, getInitialSessionQuery, server } from "./server";
import { rest } from "msw";

const logger = loglevel.getLogger("test_session");
logger.setLevel("debug");

Expand Down Expand Up @@ -64,6 +67,70 @@ describe("Session", () => {
.then((response) => response.data[0].__entity_type__)
).resolves.toEqual("Task"));

it("Should allow adding additional headers on Session", async () => {
const headers = new Promise((resolve) => {
server.use(
rest.post("http://ftrack.test/api", (req, res, ctx) => {
resolve(req.headers);
return res.once(ctx.json(getInitialSessionQuery()));
})
);
});

new Session(
credentials.serverUrl,
credentials.apiUser,
credentials.apiKey,
{
autoConnectEventHub: false,
additionalHeaders: {
"X-Test-Header": "test",
},
}
);

return expect((await headers).get("X-Test-Header")).toEqual("test");
});

it("Should support strictApi option", async () => {
const headers = new Promise((resolve) => {
server.use(
rest.post("http://ftrack.test/api", (req, res, ctx) => {
resolve(req.headers);
return res.once(ctx.json(getInitialSessionQuery()));
})
);
});

new Session(
credentials.serverUrl,
credentials.apiUser,
credentials.apiKey,
{
autoConnectEventHub: false,
strictApi: true,
}
);

return expect((await headers).get("ftrack-strict-api")).toEqual("true");
});

it("Should allow adding additional headers on calls", async () => {
const headers = new Promise((resolve) => {
server.use(
rest.post("http://ftrack.test/api", (req, res, ctx) => {
resolve(req.headers);
return res.once(ctx.json(getExampleQuery()));
})
);
});

await session.query("select name from Task limit 1", {
additionalHeaders: { "X-Test-Header": "test" },
});
return expect((await headers).get("X-Test-Header")).toEqual("test");
});

it("Should allow creating a User", () => {
const promise = session.create("User", {
username: getTestUsername(),
Expand Down
5 changes: 1 addition & 4 deletions vitest.setup.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { fetch } from "cross-fetch";
import { setupServer } from "msw/node";
import { handlers } from "./test/server";

const server = setupServer(...handlers);
import { server } from "./test/server";

// Very simple mock of XmlHttpRequest with only the parts we use
class MockXmlHttpRequest {
Expand Down