Skip to content
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
38 changes: 35 additions & 3 deletions .github/workflows/test-runner.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,23 @@ on:
branches: ["main"]

jobs:
build:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Node.js 22.x
uses: actions/setup-node@v4
with:
node-version: 22.x
cache: "npm"
- run: npm ci
- run: npm run lint

build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20.x, 22.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
Expand All @@ -27,4 +36,27 @@ jobs:
cache: "npm"
- run: npm ci
- run: npm run build --if-present
- uses: actions/upload-artifact@v4
with:
name: dist-${{ matrix.node-version }}
path: dist

test:
needs: build
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20.x, 22.x]
steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "npm"
- run: npm ci
- uses: actions/download-artifact@v4
with:
name: dist-${{ matrix.node-version }}
path: dist
- run: npm test
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,33 @@ const flag = await rocketflag.getFlag("IFldMzqP5jtv9wAL", {
});
```

## Error Handling

The SDK can throw the following errors:

- `APIError`: This error is thrown when the API returns a non-ok response. The error object contains the status code and status text of the response.
- `InvalidResponseError`: This error is thrown when the API returns an invalid response. This can happen if the response is not valid JSON or if it doesn't match the expected format.
- `NetworkError`: This error is thrown when there is a network error, such as a failed connection.

```js
import { APIError, InvalidResponseError, NetworkError } from "@rocketflag/node-sdk/errors";

try {
const flag = await rocketflag.getFlag("IFldMzqP5jtv9wAL");
// ...
} catch (error) {
if (error instanceof APIError) {
console.error(`API Error: ${error.status} ${error.statusText}`);
} else if (error instanceof InvalidResponseError) {
console.error(`Invalid Response Error: ${error.message}`);
} else if (error instanceof NetworkError) {
console.error(`Network Error: ${error.message}`);
} else {
console.error("An unknown error occurred", error);
}
}
```

## Response

The response from the API on a flag will be one of three possibilities.
Expand Down
18 changes: 18 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';

export default tseslint.config(
{
ignores: ["dist/", "coverage/"],
},
eslint.configs.recommended,
...tseslint.configs.recommended,
{
languageOptions: {
globals: {
process: "readonly",
__dirname: "readonly",
}
}
}
);
12 changes: 10 additions & 2 deletions index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { APIError, InvalidResponseError, NetworkError } from "./errors";
import createRocketflagClient from "./index";
import { FlagStatus } from "./index";
import { FlagStatus, UserContext } from "./index";

// Mock the global fetch function
global.fetch = jest.fn() as jest.Mock<Promise<Response>>;
Expand Down Expand Up @@ -119,7 +119,15 @@ describe("createRocketflagClient", () => {

it("should throw an error if flagId is not a string", async () => {
const client = createRocketflagClient();
await expect(client.getFlag(123 as any, userContext)).rejects.toThrow("flagId must be a string");
await expect(client.getFlag(123 as unknown as string, userContext)).rejects.toThrow("flagId must be a string");
});

it("should throw an error if userContext contains invalid values", async () => {
const client = createRocketflagClient();
const invalidUserContext = { cohort: { a: 1 } };
await expect(client.getFlag(flagId, invalidUserContext as unknown as UserContext)).rejects.toThrow(
"userContext values must be of type string, number, or boolean. Invalid value for key: cohort"
);
});

it("should throw a NetworkError on network error", async () => {
Expand Down
19 changes: 15 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,33 @@ export type FlagStatus = {
id: string;
};

interface UserContext {
export interface UserContext {
cohort?: string | number | boolean;
}

const createRocketflagClient = (version = DEFAULT_VERSION, apiUrl = DEFAULT_API_URL) => {
export interface RocketFlagClient {
getFlag: (flagId: string, context?: UserContext) => Promise<FlagStatus>;
}

const createRocketflagClient = (version = DEFAULT_VERSION, apiUrl = DEFAULT_API_URL): RocketFlagClient => {
const getFlag = async (flagId: string, userContext: UserContext = {}): Promise<FlagStatus> => {
if (!flagId) {
throw new Error("flagId is required");
}
if (typeof flagId !== "string") {
throw new Error("flagId must be a string");
}
if (typeof userContext !== "object") {
if (typeof userContext !== "object" || userContext === null) {
throw new Error("userContext must be an object");
}

for (const key in userContext) {
const value = userContext[key as keyof UserContext];
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
throw new Error(`userContext values must be of type string, number, or boolean. Invalid value for key: ${key}`);
}
}

const url = new URL(`${apiUrl}/${version}/flags/${flagId}`);
Object.entries(userContext).forEach(([key, value]) => {
url.searchParams.append(key, value.toString());
Expand All @@ -44,7 +55,7 @@ const createRocketflagClient = (version = DEFAULT_VERSION, apiUrl = DEFAULT_API_
let response: unknown;
try {
response = await raw.json();
} catch (error) {
} catch {
throw new InvalidResponseError("Failed to parse JSON response");
}

Expand Down
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,4 +195,4 @@ const config = {
// watchman: true,
};

module.exports = config;
export default config;
Loading