Skip to content

Commit

Permalink
Logger can be undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
d-gubert committed Dec 13, 2023
1 parent 606ac91 commit f232064
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
6 changes: 4 additions & 2 deletions deno-runtime/AppObjectRegistry.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
export type Maybe<T> = T | null | undefined;

export const AppObjectRegistry = new class {
registry: Record<string, unknown> = {};

public get(key: string): unknown {
return this.registry[key];
public get<T>(key: string): Maybe<T> {
return this.registry[key] as Maybe<T>;
}

public set(key: string, value: unknown): void {
Expand Down
6 changes: 5 additions & 1 deletion deno-runtime/lib/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class Logger {
}
const str = JSON.stringify(args, null, 2);
return str ? JSON.parse(str) : str; // force call toJSON to prevent circular references

});

this.entries.push({
Expand Down Expand Up @@ -116,6 +116,10 @@ export class Logger {
return new Date().getTime() - this.start.getTime();
}

public hasEntries(): boolean {
return this.entries.length > 0;
}

public getLogs(): ILoggerStorageEntry {
return {
appId: this.appId,
Expand Down
21 changes: 15 additions & 6 deletions deno-runtime/lib/messenger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,26 @@ export async function sendMethodNotFound(id: jsonrpc.ID): Promise<void> {
}

export async function errorResponse({ error: { message, code = -32000, data }, id }: ErrorResponseDescriptor): Promise<void> {
const logger = AppObjectRegistry.get('logger') as Logger;
const logs = logger.getLogs();
const rpc = jsonrpc.error(id, new jsonrpc.JsonRpcError(message, code, {logs, ...data}));
const logger = AppObjectRegistry.get<Logger>('logger');

if (logger?.hasEntries()) {
data.logs = logger.getLogs();
}

const rpc = jsonrpc.error(id, new jsonrpc.JsonRpcError(message, code, data));

await send(rpc);
}

export async function successResponse({ id, result }: SuccessResponseDescriptor): Promise<void> {
const logger = AppObjectRegistry.get('logger') as Logger;
const logs = logger.getLogs();
const rpc = jsonrpc.success(id, {value: result, logs});
const payload = { value: result } as Record<string, unknown>;
const logger = AppObjectRegistry.get<Logger>('logger');

if (logger?.hasEntries()) {
payload.logs = logger.getLogs();
}

const rpc = jsonrpc.success(id, payload);

await send(rpc);
}
Expand Down

0 comments on commit f232064

Please sign in to comment.