Skip to content

Commit

Permalink
Refactor encoding and decoding to use same token logic and add unit t…
Browse files Browse the repository at this point in the history
…ests (#2237)
  • Loading branch information
Alex-Tideman authored Jul 26, 2024
1 parent d15597a commit 944162d
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 65 deletions.
81 changes: 81 additions & 0 deletions src/lib/services/data-encoder.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { describe, expect, it, vi } from 'vitest';

import { codeServerRequest } from './data-encoder';

const settings = {
codec: {
endpoint: 'http://localcodecserver.com',
passAccessToken: false,
includeCredentials: false,
},
};

describe('Codec Server Requests for Decode and Encode', () => {
const payloads = { payloads: [{}] };
const namespace = 'test-namespace';

it('should send a request and return decoded payloads', async () => {
global.fetch = vi.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve(payloads),
} as Response),
);

const namespace = 'test-namespace';
const response = await codeServerRequest({
type: 'decode',
payloads,
namespace,
settings,
});
expect(response).toEqual(payloads);
});

it('should return original payloads for decode on failure', async () => {
global.fetch = vi.fn(() =>
Promise.resolve({
ok: false,
status: 500,
statusText: 'Internal Server Error',
} as Response),
);
const response = await codeServerRequest({
type: 'decode',
payloads,
namespace,
settings,
});
expect(response).toEqual(payloads);
});

it('should send a request and return encoded payloads', async () => {
global.fetch = vi.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve(payloads),
} as Response),
);

const response = await codeServerRequest({
type: 'encode',
payloads,
namespace,
settings,
});
expect(response).toEqual(payloads);
});

it('should throw an error for encode on failure', async () => {
global.fetch = vi.fn(() =>
Promise.resolve({
ok: false,
status: 500,
statusText: 'Internal Server Error',
} as Response),
);
await expect(
codeServerRequest({ type: 'encode', payloads, namespace, settings }),
).rejects.toThrow();
});
});
88 changes: 23 additions & 65 deletions src/lib/services/data-encoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ import { stringifyWithBigInt } from '$lib/utilities/parse-with-big-int';

export type PotentialPayloads = { payloads: unknown[] };

export async function decodePayloadsWithCodec({
export async function codeServerRequest({
type,
payloads,
namespace = get(page).params.namespace,
settings = get(page).data.settings,
}: {
type: 'decode' | 'encode';
payloads: PotentialPayloads;
namespace?: string;
settings?: Settings;
Expand Down Expand Up @@ -65,7 +67,7 @@ export async function decodePayloadsWithCodec({
};

const decoderResponse: Promise<PotentialPayloads> = fetch(
endpoint + '/decode',
endpoint + `/${type}`,
requestOptions,
)
.then((response) => {
Expand All @@ -74,7 +76,7 @@ export async function decodePayloadsWithCodec({
statusCode: response.status,
statusText: response.statusText,
response,
message: translate('common.decode-failed'),
message: translate(`common.${type}-failed`),
} as NetworkError;
} else {
return response.json();
Expand All @@ -87,80 +89,36 @@ export async function decodePayloadsWithCodec({
})
.catch((err: unknown) => {
setLastDataEncoderFailure(err);

return payloads;
if (type === 'decode') {
return payloads;
} else {
throw err;
}
});

return decoderResponse;
}

export async function encodePayloadsWithCodec({
export async function decodePayloadsWithCodec({
payloads,
namespace = get(page).params.namespace,
settings = get(page).data.settings,
accessToken = get(authUser).accessToken,
}: {
payloads: PotentialPayloads;
namespace?: string;
settings?: Settings;
accessToken?: string;
}): Promise<PotentialPayloads> {
const endpoint = getCodecEndpoint(settings);
const passAccessToken = getCodecPassAccessToken(settings);
const includeCredentials = getCodecIncludeCredentials(settings);

const headers = {
'Content-Type': 'application/json',
'X-Namespace': namespace,
};

if (passAccessToken) {
if (validateHttps(endpoint)) {
headers['Authorization'] = `Bearer ${accessToken}`;
} else {
setLastDataEncoderFailure();
return payloads;
}
}

const requestOptions = includeCredentials
? {
headers,
credentials: 'include' as RequestCredentials,
method: 'POST',
body: stringifyWithBigInt(payloads),
}
: {
headers,
method: 'POST',
body: stringifyWithBigInt(payloads),
};

const encoderResponse: Promise<PotentialPayloads> = fetch(
endpoint + '/encode',
requestOptions,
)
.then((response) => {
if (has(response, 'ok') && !response.ok) {
throw {
statusCode: response.status,
statusText: response.statusText,
response,
message: translate('common.encode-failed'),
} as NetworkError;
} else {
return response.json();
}
})
.then((response) => {
setLastDataEncoderSuccess();

return response;
})
.catch((err: unknown) => {
setLastDataEncoderFailure(err);
throw err;
});
return codeServerRequest({ type: 'decode', payloads, namespace, settings });
}

return encoderResponse;
export async function encodePayloadsWithCodec({
payloads,
namespace = get(page).params.namespace,
settings = get(page).data.settings,
}: {
payloads: PotentialPayloads;
namespace?: string;
settings?: Settings;
}): Promise<PotentialPayloads> {
return codeServerRequest({ type: 'encode', payloads, namespace, settings });
}

0 comments on commit 944162d

Please sign in to comment.