Skip to content

Commit

Permalink
Merge pull request #2 from nearup-io/event-listeners
Browse files Browse the repository at this point in the history
Nodb event listeners
  • Loading branch information
tot-kristian authored Jul 23, 2024
2 parents d3dd058 + 752971e commit 55dfa04
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 14 deletions.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"@changesets/cli": "^2.27.7",
"@types/jest": "^29.5.12",
"@types/node": "^20.14.9",
"@types/ws": "^8.5.11",
"jest": "^29.7.0",
"prettier": "^3.3.2",
"ts-jest": "^29.1.5",
Expand All @@ -49,6 +50,7 @@
},
"dependencies": {
"axios": "^1.7.2",
"dotenv": "^16.4.5"
"dotenv": "^16.4.5",
"ws": "^8.18.0"
}
}
27 changes: 27 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

72 changes: 72 additions & 0 deletions src/nodb-event-listener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import WebSocket from "ws";
import { NodbError } from "./errors";

class NodbEventListener {
protected socket: WebSocket | undefined;

protected connect(props: {
baseUrl: string;
appName: string;
envName?: string;
token: string;
}) {
if (!props.token) {
throw new NodbError("Token is missing!");
}
const envUrlPart = props.envName ? `/${props.envName}` : "";

const formattedBaseUrl = props.baseUrl
.replace("http://", "ws://")
.replace("https://", "wss://");
this.socket = new WebSocket(
`${formattedBaseUrl}/ws/${props.appName}${envUrlPart}`,
{
headers: {
token: props.token,
},
},
);

this.socket.on("open", () => {
console.log("Connected to socket");
});

this.socket.onerror = () => {
throw new NodbError(`Something went wrong with socket!`);
};

this.listenForMessages();
}

protected listenForMessages() {
this.socket?.on("message", (data) => {
const message = data.toString();
try {
const {
type,
appName,
envName,
data: messageData,
} = JSON.parse(message) as {
type: string;
appName: string;
envName: string;
data: any;
};
console.log(`Operation ${type.toUpperCase()}`);
console.log(
`Affected environment: ${JSON.stringify({ appName, envName }, null, 2)}`,
);
console.log(`Data: ${JSON.stringify(messageData, null, 2)}`);
} catch (err) {
console.error("Error parsing JSON:", err);
}
});
}

public disconnectFromSocket() {
this.socket?.close();
}
}

export default NodbEventListener;
35 changes: 22 additions & 13 deletions src/nodb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,19 @@ import {
} from "./types";
import { NodbError } from "./errors";
import axios, { Axios, AxiosError } from "axios";
import NodbEventListener from "./nodb-event-listener";

class Nodb {
class Nodb extends NodbEventListener {
private readonly baseUrl: string;
private readonly axios: Axios;

private token?: string;
constructor({ token, baseUrl }: NodbConstructor) {
super();
if (!baseUrl) {
throw new NodbError("Missing one of the required dependencies!");
}
this.baseUrl = baseUrl;
this.token = token;
this.axios = axios.create({
headers: {
"Content-Type": "application/json",
Expand All @@ -41,7 +44,7 @@ class Nodb {
(response) => response,
(error: AxiosError) => {
if (error.response && error.response.status >= 400) {
throw new NodbError(error.response.data as string);
throw new NodbError(JSON.stringify(error.response.data, null, 2));
}
return Promise.reject(error);
},
Expand All @@ -60,6 +63,7 @@ class Nodb {
}

public setToken(token: string): void {
this.token = token;
this.axios.defaults.headers.common.token = token;
}

Expand Down Expand Up @@ -117,14 +121,14 @@ class Nodb {
props: BaseAPIProps & PatchRequestBody,
): Promise<string[]> {
const { payload, token, ...urlProps } = props;
const request = await this.axios.put<{ ids: string[] }>(
const response = await this.axios.put<{ ids: string[] }>(
this.generateUrl(urlProps),
payload,
{
...(token && { headers: { token } }),
},
);
return request.data.ids;
return response.data.ids;
}

async replaceEntity(
Expand Down Expand Up @@ -212,7 +216,6 @@ class Nodb {
environmentDescription,
},
);

return result.data;
}

Expand All @@ -228,7 +231,6 @@ class Nodb {
},
{ ...(token && { headers: { token } }) },
);

return result.data;
}

Expand All @@ -242,7 +244,6 @@ class Nodb {
`/apps/${appName}/${environmentName}`,
{ ...(token && { headers: { token } }) },
);

return result.data.found;
}

Expand All @@ -255,7 +256,6 @@ class Nodb {
`/apps/${appName}`,
{ ...(token && { headers: { token } }) },
);

return result.data.found;
}

Expand All @@ -272,7 +272,6 @@ class Nodb {
},
{ ...(token && { headers: { token } }) },
);

return result.data;
}

Expand All @@ -290,7 +289,6 @@ class Nodb {
},
{ ...(token && { headers: { token } }) },
);

return result.data;
}

Expand All @@ -304,7 +302,6 @@ class Nodb {
`/tokens/${appName}/${tokenToBeRevoked}`,
{ ...(token && { headers: { token } }) },
);

return result.data.success;
}

Expand All @@ -319,9 +316,21 @@ class Nodb {
`/tokens/${appName}/${envName}/${tokenToBeRevoked}`,
{ ...(token && { headers: { token } }) },
);

return result.data.success;
}

connectToSocket(props: {
appName: string;
envName?: string;
token?: string;
}): void {
this.connect({
appName: props.appName,
envName: props.envName,
baseUrl: this.baseUrl,
token: props.token || this.token || "",
});
}
}

export default Nodb;

0 comments on commit 55dfa04

Please sign in to comment.