Skip to content

Commit

Permalink
fix(core): resolve api constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
juanrgm committed May 10, 2022
1 parent 0fd78a8 commit c85dfae
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/silver-kids-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@smcp/core": patch
---

Fix `api` option
4 changes: 2 additions & 2 deletions packages/core/src/ServerController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ConfigsType, DataType } from "./utils/ejson";
import { getObjectValue, merge } from "./utils/object";
import { getObjectValue, isClass, merge } from "./utils/object";
import { parsePath } from "./utils/proxy";
import {
MessageType,
Expand Down Expand Up @@ -44,7 +44,7 @@ export class ServerController<TApi, TClientKey> {
const [classLevels, method] = parsePath(path);
const api = this.options.api;
const Constructor = getObjectValue(
typeof api === "function"
typeof api === "function" && !isClass(api)
? (api as () => Record<string, unknown>)()
: (api as Record<string, unknown>),
classLevels
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/utils/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ export enum IterationTypeEnum {
Object,
}

export function isClass(value: unknown) {
return typeof value === "function" && /^\s*class\s+/.test(value.toString());
}

export function isInstanceObject(
value: unknown
): value is Record<string, unknown> {
Expand Down
23 changes: 23 additions & 0 deletions packages/core/test/Server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,26 @@ describe("Server.options.container", () => {
await server.stop();
});
});

describe("Server.options.api", () => {
it("resolves constructor", async () => {
class Api {
get() {
return true;
}
}
const server = new Server({
container,
api: Api,
});

await server.start(0);

const client = new Client<Api>({
url: { port: server.port },
});

expect(await client.api.get()).toBe(true);
await server.stop();
});
});

0 comments on commit c85dfae

Please sign in to comment.