Skip to content

Commit

Permalink
Moved from enum to union of strings, fixed tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lucianHymer committed Jan 24, 2023
1 parent 947d386 commit bc4b965
Show file tree
Hide file tree
Showing 11 changed files with 48 additions and 63 deletions.
15 changes: 6 additions & 9 deletions app/__tests__/components/RefreshModal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@ describe("RefreshStampModal", () => {
mockUserContext,
{
...mockCeramicContext,
ceramicErrors: {
error: true,
stamps: ["streamid"],
passportLoadResponse: {
status: "PassportError",
},
},
<RefreshStampModal isOpen={true} onClose={jest.fn()} />
Expand All @@ -48,9 +47,8 @@ describe("RefreshStampModal", () => {
mockUserContext,
{
...mockCeramicContext,
ceramicErrors: {
error: true,
stamps: ["streamid"],
passportLoadResponse: {
status: "PassportError",
},
},
<RefreshStampModal isOpen={true} onClose={jest.fn()} />
Expand All @@ -65,9 +63,8 @@ describe("RefreshStampModal", () => {
mockUserContext,
{
...mockCeramicContext,
ceramicErrors: {
error: true,
stamps: ["streamid"],
passportLoadResponse: {
status: "PassportError",
},
},
<RefreshStampModal isOpen={true} onClose={jest.fn()} />
Expand Down
12 changes: 3 additions & 9 deletions app/__tests__/pages/Dashboard.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,7 @@ describe("when a user clicks on the Passport logo", () => {
mockUserContext,
{
...mockCeramicContext,
ceramicErrors: {
error: true,
stamps: ["streamid"],
},
passportHasErrors: () => true,
},
<Router>
<Dashboard />
Expand All @@ -246,17 +243,14 @@ describe("when a user clicks on the Passport logo", () => {
mockUserContext,
{
...mockCeramicContext,
ceramicErrors: {
error: true,
stamps: ["streamid"],
},
passportHasErrors: () => true,
},
<Router>
<Dashboard />
</Router>
);

await fireEvent.click(screen.getByText("Reset Passport"));
fireEvent.click(screen.getByText("Reset Passport"));
await waitFor(() => {
expect(screen.getByText("Refresh Modal")).toBeInTheDocument();
});
Expand Down
16 changes: 7 additions & 9 deletions app/context/ceramicContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -517,12 +517,13 @@ export const CeramicContextProvider = ({ children }: { children: any }) => {
const { status, errorDetails, passport } = await database.getPassport();

switch (status) {
case (PassportLoadStatus.PassportError, PassportLoadStatus.DoesNotExist):
case "PassportError":
case "DoesNotExist":
const passportCacaoError = await database.checkPassportCACAOError();
if (passportCacaoError) {
datadogRum.addError("Passport CACAO error -- error thrown on initial fetch", { address });
} else {
if (status === PassportLoadStatus.DoesNotExist) handleCreatePassport();
if (status === "DoesNotExist") handleCreatePassport();
else {
// something is wrong with Ceramic...
datadogRum.addError("Ceramic connection failed", { address });
Expand All @@ -531,10 +532,10 @@ export const CeramicContextProvider = ({ children }: { children: any }) => {
}
}
break;
case PassportLoadStatus.PassportStampError:
case "PassportStampError":
// Handled in the refresh
break;
case PassportLoadStatus.Success:
case "Success":
default:
const cleanedPassport = cleanPassport(passport, database) as Passport;
hydrateAllProvidersState(cleanedPassport);
Expand Down Expand Up @@ -569,7 +570,7 @@ export const CeramicContextProvider = ({ children }: { children: any }) => {
const handleCheckRefreshPassport = async (): Promise<boolean> => {
let success = true;
if (ceramicDatabase && passportLoadResponse) {
let passportHasError = passportLoadResponse.status === PassportLoadStatus.PassportError;
let passportHasError = passportLoadResponse.status === "PassportError";
let failedStamps = passportLoadResponse.errorDetails?.stampStreamIds || [];
try {
if (passportHasError) {
Expand Down Expand Up @@ -661,10 +662,7 @@ export const CeramicContextProvider = ({ children }: { children: any }) => {
};

const passportHasErrors = (): boolean => {
if (passportLoadResponse)
return [PassportLoadStatus.PassportError || PassportLoadStatus.PassportStampError].includes(
passportLoadResponse.status
);
if (passportLoadResponse) return ["PassportError" || "PassportStampError"].includes(passportLoadResponse.status);
else return false;
};

Expand Down
10 changes: 6 additions & 4 deletions database-client/__tests__/CeramicDatabase.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { PassportLoadStatus } from "@gitcoin/passport-types";
import { Passport, VerifiableCredential, Stamp, PROVIDER_ID } from "@gitcoin/passport-types";
import { DID } from "dids";
import { Ed25519Provider } from "key-did-provider-ed25519";
import { getResolver } from "key-did-resolver";
Expand Down Expand Up @@ -44,7 +43,8 @@ describe("Verify Ceramic Database", () => {
const { passport, status } = await ceramicDatabase.getPassport();

// We do not expect to have any passport, hence `false` should be returned
expect(status).toEqual(PassportLoadStatus.DoesNotExist);
const expectedStatus: PassportLoadStatus = "DoesNotExist";
expect(status).toEqual(expectedStatus);
expect(passport).toEqual(undefined);
expect(spyStoreGet).toBeCalledTimes(1);
expect(spyStoreGet).toBeCalledWith("Passport");
Expand All @@ -58,7 +58,8 @@ describe("Verify Ceramic Database", () => {
const { passport, status } = await ceramicDatabase.getPassport();

// We do not expect to have any passport, hence `false` should be returned
expect(status).toEqual(PassportLoadStatus.DoesNotExist);
const expectedStatus: PassportLoadStatus = "DoesNotExist";
expect(status).toEqual(expectedStatus);
expect(passport).toEqual(undefined);
expect(spyStoreGet).toBeCalledTimes(1);
expect(spyStoreGet).toBeCalledWith("Passport");
Expand Down Expand Up @@ -275,7 +276,8 @@ describe("Verify Ceramic Database", () => {
},
]);

expect(passport.status).toBe(PassportLoadStatus.PassportStampError);
const expectedStatus: PassportLoadStatus = "PassportStampError";
expect(passport.status).toBe(expectedStatus);
expect(passport.errorDetails?.stampStreamIds).toEqual(["ceramic://credential-1"]);
});
});
Expand Down
24 changes: 12 additions & 12 deletions database-client/integration-tests/ceramicDatabaseTest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// import { PassportWithErrors } from "./../../types/src/index.d";
import { Passport, VerifiableCredential, Stamp, PROVIDER_ID } from "@gitcoin/passport-types";
import { PassportLoadStatus, Passport, VerifiableCredential, Stamp, PROVIDER_ID } from "@gitcoin/passport-types";
import { DID } from "dids";
import { Ed25519Provider } from "key-did-provider-ed25519";
import { getResolver } from "key-did-resolver";
Expand Down Expand Up @@ -53,9 +52,10 @@ describe("when there is no passport for the given did", () => {
});

it("getPassport returns false", async () => {
const actualPassport = await ceramicDatabase.getPassport();
const { passport, status, errorDetails } = await ceramicDatabase.getPassport();

expect(actualPassport).toEqual(false);
const expectedStatus: PassportLoadStatus = "DoesNotExist";
expect(status).toEqual(expectedStatus);
});
});

Expand Down Expand Up @@ -210,15 +210,15 @@ describe("when there is an existing passport with stamps for the given did", ()
});

it("getPassport retrieves the passport and stamps from ceramic", async () => {
const actualPassport = await ceramicDatabase.getPassport();
const { passport } = await ceramicDatabase.getPassport();

const formattedDate = new Date(actualPassport.passport["issuanceDate"]);
const formattedDate = new Date(passport["issuanceDate"]);

expect(actualPassport.passport).toBeDefined();
expect(passport).toBeDefined();
expect(formattedDate.getDay()).toEqual(existingPassport.issuanceDate.getDay());
expect(formattedDate.getMonth()).toEqual(existingPassport.issuanceDate.getMonth());
expect(formattedDate.getFullYear()).toEqual(existingPassport.issuanceDate.getFullYear());
expect(actualPassport.passport.stamps[0]).toEqual(ensStampFixture);
expect(passport.stamps[0]).toEqual(ensStampFixture);
});

it("addStamp adds a stamp to passport", async () => {
Expand Down Expand Up @@ -489,17 +489,17 @@ describe("when loading a stamp from a passport fails", () => {
});

it("ignores the failed stamp and only returns the successfully loaded stamps", async () => {
const passport = await ceramicDatabase.getPassport();
const { passport } = await ceramicDatabase.getPassport();

// We only expect 2 results: Ens and Google stamps
expect(passport.passport.stamps.length).toEqual(2);
expect(passport.stamps.length).toEqual(2);
expect(
passport.passport.stamps.findIndex((stamp) => {
passport.stamps.findIndex((stamp) => {
return stamp && stamp.credential.credentialSubject.provider === "Ens";
})
).toEqual(0);
expect(
passport.passport.stamps.findIndex((stamp) => {
passport.stamps.findIndex((stamp) => {
return stamp && stamp.credential.credentialSubject.provider === "Google";
})
).toEqual(1);
Expand Down
11 changes: 5 additions & 6 deletions database-client/src/ceramicClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ export class CeramicDatabase implements DataStorageBase {

async getPassport(): Promise<PassportLoadResponse> {
let passport: Passport;
let status = PassportLoadStatus.Success;
let status: PassportLoadStatus = "Success";
let errorDetails: PassportLoadErrorDetails;

try {
Expand All @@ -180,13 +180,13 @@ export class CeramicDatabase implements DataStorageBase {

// According to the logs, it does happen that passport is sometimes an empty object {}
// We treat this case as an non-existent passport
if (!ceramicPassport?.stamps) status = PassportLoadStatus.DoesNotExist;
if (!ceramicPassport?.stamps) status = "DoesNotExist";
else {
const { successfulStamps, cacaoErrorStampIds } = await this.loadStamps(ceramicPassport);

if (cacaoErrorStampIds.length) {
errorDetails = { stampStreamIds: cacaoErrorStampIds };
status = PassportLoadStatus.PassportStampError;
status = "PassportStampError";
}

passport = {
Expand All @@ -198,7 +198,7 @@ export class CeramicDatabase implements DataStorageBase {
await this.pinCurrentPassport();
}
} catch (e) {
status = PassportLoadStatus.PassportError;
status = "PassportError";
this.logger.error(`Error when loading passport for did ${this.did}:` + e.toString(), { error: e });
} finally {
return {
Expand Down Expand Up @@ -398,10 +398,9 @@ export class CeramicDatabase implements DataStorageBase {
}

async function getFulfilledPromises<T>(promises: Promise<T>[]): Promise<T[]> {
// Wait for all stamp loading to be settled
const promiseStatuses = await Promise.allSettled(promises);

// Filter out only the successfully loaded stamps
// Filter out only the successful promises
const isFulfilled = <T>(input: PromiseSettledResult<T>): input is PromiseFulfilledResult<T> =>
input.status === "fulfilled";

Expand Down
1 change: 0 additions & 1 deletion types/.gitignore

This file was deleted.

3 changes: 1 addition & 2 deletions types/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
"name": "@gitcoin/passport-types",
"version": "1.0.0",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"types": "src/index.d.ts",
"scripts": {
"build": "tsc -b .",
"clean": "rimraf dist *.tsbuildinfo",
Expand Down
File renamed without changes.
9 changes: 2 additions & 7 deletions types/src/index.ts → types/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export type IssuedCredential = {
credential: VerifiableCredential;
};

// Issued Credential and support matterial returned when fetching the VerifiableCredential
// Issued Credential and support material returned when fetching the VerifiableCredential
export type VerifiableCredentialRecord = {
signature: string;
challenge: VerifiableCredential;
Expand All @@ -139,12 +139,7 @@ export type Passport = {
stamps: Stamp[];
};

export enum PassportLoadStatus {
Success,
DoesNotExist,
PassportError,
PassportStampError,
}
export type PassportLoadStatus = "Success" | "DoesNotExist" | "PassportError" | "PassportStampError";

export type PassportLoadErrorDetails = {
stampStreamIds: string[];
Expand Down
10 changes: 6 additions & 4 deletions types/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
{
"extends": "../tsconfig.settings.json",
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"outDir": "dist"
"composite": true,
"declaration": true,
"rootDir": ".",
"types": ["node"],
"outDir": "/tmp/tsc-output"
},
"include": ["src/**/*"]
"include": ["src"]
}

0 comments on commit bc4b965

Please sign in to comment.