Skip to content

Commit

Permalink
Merge pull request #378 from docknetwork/feat/remove-axios
Browse files Browse the repository at this point in the history
Remove Axios in favor of fetch
  • Loading branch information
cykoder authored Nov 10, 2023
2 parents 0ac51ed + 0f0dafb commit 2c3882a
Show file tree
Hide file tree
Showing 14 changed files with 84 additions and 51 deletions.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@docknetwork/sdk",
"version": "6.8.0",
"version": "6.8.1",
"main": "index.js",
"license": "MIT",
"repository": {
Expand Down Expand Up @@ -104,7 +104,6 @@
"@juanelas/base64": "^1.0.5",
"@polkadot/api": "9.7.1",
"@transmute/json-web-signature": "^0.7.0-unstable.80",
"axios": "0.27.2",
"base64url": "3.0.1",
"blake2b": "2.1.4",
"bs58": "5.0.0",
Expand Down
4 changes: 2 additions & 2 deletions src/modules/schema.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { canonicalize } from 'json-canonicalize';
import { validate } from 'jsonschema';
import axios from 'axios';

import { hexDIDToQualified } from '../utils/did';
import { getSignatureFromKeyringPair } from '../utils/misc';
Expand All @@ -12,6 +11,7 @@ import {

// Supported schemas
import JSONSchema07 from '../utils/vc/schemas/schema-draft-07';
import jsonFetch from '../utils/json-fetch';

export default class Schema {
/**
Expand Down Expand Up @@ -165,7 +165,7 @@ export default class Schema {
return JSONSchema07;
}
// Fetch the URI and expect a JSON response
const { data: doc } = await axios.get(schemaUrl);
const doc = await jsonFetch(schemaUrl);
if (typeof doc === 'object') {
return doc;
}
Expand Down
8 changes: 4 additions & 4 deletions src/resolver/did/universal-resolver.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';
import { NoDIDError } from '../../utils/did';
import { Resolver, WILDCARD } from '../generic';
import jsonFetch from '../../utils/json-fetch';

/**
* Resolves `DID`s with wildcard method: `did:*:`.
Expand Down Expand Up @@ -36,17 +36,17 @@ export default class UniversalResolver extends Resolver {
hashIndex === -1 ? did : did.slice(0, hashIndex).trim(),
);
try {
const resp = await axios.get(`${this.idUrl}${encodedDid}`, {
const resp = await jsonFetch(`${this.idUrl}${encodedDid}`, {
headers: {
Accept:
'application/ld+json;profile="https://w3id.org/did-resolution"',
},
});

// Sometimes didDocument doesnt exist, if so return data as document
return resp.data.didDocument || resp.data;
return resp.didDocument || resp;
} catch (error) {
if (error.isAxiosError) {
if (error.statusCode === 404) {
throw new NoDIDError(did);
}

Expand Down
32 changes: 32 additions & 0 deletions src/utils/json-fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export class JSONFetchError extends Error {
constructor(message, statusCode) {
super(message);

this.statusCode = statusCode;
}
}

export default async function jsonFetch(url, options) {
if (url.startsWith('blob:')) {
throw new Error('Unsupported protocol blob:');
}

let response;
try {
response = await fetch(url, options);
} catch (e) {
throw new Error(`Fetch failed for URL: ${url}`);
}
if (response.ok) {
let doc;
try {
doc = await response.json();
} catch (e) {
throw new Error(`URL: ${url} is not JSON`);
}
return doc;
} else {
// Handle the case when the fetch request fails (e.g., non-2xx response status)
throw new JSONFetchError('Failed to fetch data', response.status);
}
}
4 changes: 2 additions & 2 deletions src/utils/vc/document-loader.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';
import cachedUris from './contexts';
import Resolver from "../../resolver/generic/resolver"; // eslint-disable-line
import jsonFetch from '../json-fetch';

function parseEmbeddedDataURI(embedded) {
// Strip new lines
Expand Down Expand Up @@ -63,7 +63,7 @@ function documentLoader(resolver = null) {
if (cachedData) {
document = cachedData;
} else {
const { data: doc } = await axios.get(uriString);
const doc = await jsonFetch(uriString);
cachedUris.set(cacheKey, doc);
document = doc;
}
Expand Down
4 changes: 2 additions & 2 deletions tests/cached-document-loader.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';
import contexts from '../src/utils/vc/contexts';
import network_cache from './network-cache';
import jsonFetch from '../src/utils/json-fetch';

// global document cache, replaces the internet and acts as a did method
const documentRegistry = {};
Expand All @@ -17,7 +17,7 @@ export async function documentLoader(url) {
if (!(url.startsWith('http://') || url.startsWith('https://'))) {
throw new Error(`failed to resolve ${url}`);
}
documentRegistry[url] = (await axios.get(url)).data;
documentRegistry[url] = await jsonFetch(url);
console.warn(
'Unit test is making web requests. This is slow. Please update ./test/network-cache.js',
'with: ',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Mock axios
// Mock fetch
import { randomAsHex } from '@polkadot/util-crypto';
import jsonld from 'jsonld';
import mockAxios from '../mocks/axios';
import mockFetch from '../mocks/fetch';

import {
createNewDockDID,
Expand All @@ -18,7 +18,7 @@ import {
import { getKeyDoc } from '../../src/utils/vc/helpers';
import { createPresentation } from '../create-presentation';

mockAxios();
mockFetch();

// DID and seed for
const issuerDID = createNewDockDID();
Expand Down
6 changes: 3 additions & 3 deletions tests/integration/issuing.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Mock axios
// Mock fetch
import { randomAsHex } from '@polkadot/util-crypto';
import mockAxios from '../mocks/axios';
import mockFetch from '../mocks/fetch';

import { createNewDockDID } from '../../src/utils/did';

Expand All @@ -15,7 +15,7 @@ import { generateEcdsaSecp256k1Keypair } from '../../src/utils/misc';
import { issueCredential, verifyCredential } from '../../src/utils/vc/index';
import { getKeyDoc } from '../../src/utils/vc/helpers';

mockAxios();
mockFetch();

// 1st issuer's DID.
const issuer1DID = createNewDockDID();
Expand Down
17 changes: 0 additions & 17 deletions tests/mocks/axios.js

This file was deleted.

27 changes: 27 additions & 0 deletions tests/mocks/fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import networkCache from '../network-cache';

// Mock the global fetch function
global.fetch = jest.fn();

// Function to set up a mock response for fetch
const mockFetchResponse = (status, data) => {
const response = new Response(JSON.stringify(data), {
status,
headers: {
'Content-type': 'application/json',
},
});
return Promise.resolve(response);
};

export default function mockFetch() {
// Set up a mock response for all GET requests
fetch.mockImplementation((url) => {
if (networkCache[url]) {
return mockFetchResponse(200, networkCache[url]);
}

console.error(`Test should cache this URL: ${url}`);
throw new Error(`Test should cache this URL: ${url}`);
});
}
6 changes: 3 additions & 3 deletions tests/unit/issuing.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Mock axios
import mockAxios from '../mocks/axios';
// Mock fetch
import mockFetch from '../mocks/fetch';

import {
issueCredential,
Expand All @@ -12,7 +12,7 @@ import VerifiableCredential from '../../src/verifiable-credential';
import VerifiablePresentation from '../../src/verifiable-presentation';
import testingKeys from '../test-keys';

mockAxios();
mockFetch();

// Test constants
const issuanceDate = '2020-04-15T09:05:35Z';
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/presigned-validation.test.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// Mock axios
import mockAxios from '../mocks/axios';
// Mock fetch
import mockFetch from '../mocks/fetch';

import {
verifyCredential,
} from '../../src/utils/vc/index';

mockAxios();
mockFetch();

const controllerUrl = 'https://gist.githubusercontent.com/lovesh/312d407e3a16be0e7d5e43169e824958/raw';
const keyUrl = 'https://gist.githubusercontent.com/lovesh/67bdfd354cfaf4fb853df4d6713f4610/raw';
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/schema.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Mock axios
// Mock fetch
import { cryptoWaitReady } from '@polkadot/util-crypto';

import VerifiableCredential from '../../src/verifiable-credential';
Expand Down
10 changes: 1 addition & 9 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4733,14 +4733,6 @@ aws4@^1.8.0:
resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.11.0.tgz#d61f46d83b2519250e2784daf5b09479a8b41c59"
integrity sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==

[email protected]:
version "0.27.2"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.27.2.tgz#207658cc8621606e586c85db4b41a750e756d972"
integrity sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==
dependencies:
follow-redirects "^1.14.9"
form-data "^4.0.0"

b4a@^1.0.1:
version "1.6.1"
resolved "https://registry.yarnpkg.com/b4a/-/b4a-1.6.1.tgz#9effac93a469a868d024e16fd77162c653544cbd"
Expand Down Expand Up @@ -7086,7 +7078,7 @@ [email protected]:
resolved "https://registry.yarnpkg.com/fn.name/-/fn.name-1.1.0.tgz#26cad8017967aea8731bc42961d04a3d5988accc"
integrity sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==

follow-redirects@^1.14.9, follow-redirects@^1.5.1:
follow-redirects@^1.5.1:
version "1.15.2"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz#b460864144ba63f2681096f274c4e57026da2c13"
integrity sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==
Expand Down

0 comments on commit 2c3882a

Please sign in to comment.