Skip to content

Commit

Permalink
fix: make trigger an error to occur when re-registering a handler in …
Browse files Browse the repository at this point in the history
…a submethod after registering it with an argument.
  • Loading branch information
sor4chi committed Nov 30, 2023
1 parent 8d1fa0d commit c95739e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
21 changes: 7 additions & 14 deletions packages/hono-do/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,37 +73,30 @@ export function generateHonoObject<
_handlers.webSocketError?.(...args, this.state, this.vars);
};

const isCalledMap = new Map<string, boolean>();

honoObject.alarm = function (handler: AlarmHandler) {
const name = "alarm";
if (isCalledMap.get(name)) throw Errors.handlerAlreadySet(name);
if (_handlers.alarm) throw Errors.handlerAlreadySet("alarm");
_handlers.alarm = handler;
isCalledMap.set(name, true);
return honoObject;
};

honoObject.webSocketMessage = function (handler: WebSocketMessageHandler) {
const name = "webSocketMessage";
if (isCalledMap.get(name)) throw Errors.handlerAlreadySet(name);
if (_handlers.webSocketMessage)
throw Errors.handlerAlreadySet("webSocketMessage");
_handlers.webSocketMessage = handler;
isCalledMap.set(name, true);
return honoObject;
};

honoObject.webSocketClose = function (handler: WebSocketCloseHandler) {
const name = "webSocketClose";
if (isCalledMap.get(name)) throw Errors.handlerAlreadySet(name);
if (_handlers.webSocketClose)
throw Errors.handlerAlreadySet("webSocketClose");
_handlers.webSocketClose = handler;
isCalledMap.set(name, true);
return honoObject;
};

honoObject.webSocketError = function (handler: WebSocketErrorHandler) {
const name = "webSocketError";
if (isCalledMap.get(name)) throw Errors.handlerAlreadySet(name);
if (_handlers.webSocketError)
throw Errors.handlerAlreadySet("webSocketError");
_handlers.webSocketError = handler;
isCalledMap.set(name, true);
return honoObject;
};

Expand Down
9 changes: 9 additions & 0 deletions packages/hono-do/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,15 @@ describe("generateHonoObject", () => {
Errors.handlerAlreadySet("webSocketMessage"),
);
});

it("should error when multiple handler set to same Hono Object, with other way", async () => {
const DO = generateHonoObject("/", () => {}, {
alarm: async () => {},
});
expect(() => DO.alarm(async () => {})).toThrowError(
Errors.handlerAlreadySet("alarm"),
);
});
});

describe("Worker", () => {
Expand Down

0 comments on commit c95739e

Please sign in to comment.