transit-kit 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1 +1,4 @@
1
- # declarative-server
1
+ # transit-kit
2
+
3
+ [![CI](https://github.com/D4rkr34lm/transit-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/D4rkr34lm/transit-kit/actions/workflows/ci.yml)
4
+ [![Coverage Status](https://coveralls.io/repos/github/D4rkr34lm/transit-kit/badge.svg?branch=main)](https://coveralls.io/github/D4rkr34lm/transit-kit?branch=main)
@@ -1,2 +1,11 @@
1
+ import { HttpMethod } from "../server/constants/HttpMethods";
2
+ import { ApiEndpointDefinition } from "../server/handlers/api/EndpointDefinition";
3
+ import { GenericResponseSchemaMap } from "../server/handlers/api/responses";
4
+ import { ZodType } from "zod";
1
5
  import { OpenAPIV3 } from "openapi-types";
6
+ declare function translateToOpenAPIPathItem(definition: ApiEndpointDefinition<string, HttpMethod, ZodType | undefined, ZodType | undefined, GenericResponseSchemaMap>): [string, OpenAPIV3.PathItemObject];
2
7
  export declare function generateOpenApiDoc(targetPath: string): Promise<OpenAPIV3.Document<{}>>;
8
+ export declare const __TEST_EXPORTS: {
9
+ translateToOpenAPIPathItem: typeof translateToOpenAPIPathItem;
10
+ };
11
+ export {};
@@ -128,3 +128,6 @@ export async function generateOpenApiDoc(targetPath) {
128
128
  throw new Error("The specified module does not export a valid server instance.");
129
129
  }
130
130
  }
131
+ export const __TEST_EXPORTS = {
132
+ translateToOpenAPIPathItem,
133
+ };
@@ -0,0 +1,65 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import z from "zod";
3
+ import { createApiEndpointHandler } from "../server";
4
+ import { __TEST_EXPORTS } from "./generateOpenApi";
5
+ const { translateToOpenAPIPathItem } = __TEST_EXPORTS;
6
+ describe("translateToOpenAPIPathItem", () => {
7
+ it("should translate endpoint definitions to OpenAPI path items", () => {
8
+ const { definition } = createApiEndpointHandler({
9
+ method: "get",
10
+ path: "/users/:id",
11
+ meta: {
12
+ name: "getUser",
13
+ description: "Retrieve a user by ID",
14
+ group: "User",
15
+ },
16
+ responseSchemas: {
17
+ 200: {
18
+ dataType: "application/json",
19
+ dataSchema: z.string(),
20
+ },
21
+ },
22
+ }, async (req) => {
23
+ return {
24
+ code: 200,
25
+ dataType: "application/json",
26
+ json: req.params.id,
27
+ };
28
+ });
29
+ const [path, pathItem] = translateToOpenAPIPathItem(definition);
30
+ const expectedPath = "/users/{id}";
31
+ const expectedSchema = {
32
+ $schema: "https://json-schema.org/draft/2020-12/schema",
33
+ type: "string",
34
+ };
35
+ const expectedPathItem = {
36
+ get: {
37
+ operationId: "getUser",
38
+ summary: "Retrieve a user by ID",
39
+ tags: ["User"],
40
+ description: "Retrieve a user by ID",
41
+ parameters: [
42
+ {
43
+ description: "Path parameter :id",
44
+ name: "id",
45
+ in: "path",
46
+ required: true,
47
+ schema: { type: "string" },
48
+ },
49
+ ],
50
+ responses: {
51
+ "200": {
52
+ description: "Response for status code 200",
53
+ content: {
54
+ "application/json": {
55
+ schema: expectedSchema,
56
+ },
57
+ },
58
+ },
59
+ },
60
+ },
61
+ };
62
+ expect(path).toBe(expectedPath);
63
+ expect(pathItem).toEqual(expectedPathItem);
64
+ });
65
+ });
@@ -0,0 +1,9 @@
1
+ import z from "zod";
2
+ import { HttpMethod } from "../../constants/HttpMethods";
3
+ import { ApiEndpointDefinition } from "./EndpointDefinition";
4
+ import { HandlerForDefinition } from "./HandlerFromDefinition";
5
+ import { GenericResponseSchemaMap } from "./responses";
6
+ export interface ApiEndpoint<Path extends string = string, Method extends HttpMethod = HttpMethod, RequestBody extends z.ZodType | undefined = undefined | z.ZodType, Query extends z.ZodType | undefined = undefined | z.ZodType, ResponseMap extends GenericResponseSchemaMap = GenericResponseSchemaMap, Handler extends HandlerForDefinition<Path, RequestBody, Query, ResponseMap> = HandlerForDefinition<Path, RequestBody, Query, ResponseMap>> {
7
+ definition: ApiEndpointDefinition<Path, Method, RequestBody, Query, ResponseMap>;
8
+ handler: Handler;
9
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -6,7 +6,7 @@ export interface ApiEndpointMeta {
6
6
  group: string;
7
7
  description: string;
8
8
  }
9
- export type ApiEndpointDefinition<Path extends string, Method extends HttpMethod, RequestBody extends z.ZodType | undefined, Query extends z.ZodType | undefined, ResponseMap extends GenericResponseSchemaMap> = {
9
+ export type ApiEndpointDefinition<Path extends string = string, Method extends HttpMethod = HttpMethod, RequestBody extends z.ZodType | undefined = z.ZodType | undefined, Query extends z.ZodType | undefined = z.ZodType | undefined, ResponseMap extends GenericResponseSchemaMap = GenericResponseSchemaMap> = {
10
10
  meta: ApiEndpointMeta;
11
11
  path: Path;
12
12
  method: Method;
@@ -1,6 +1,6 @@
1
1
  import { Request } from "express";
2
2
  import { HttpStatusCodes } from "../../constants/HttpStatusCodes";
3
3
  import { GenericResponse } from "./responses";
4
- export type ApiEndpointHandler<PathParams extends Record<string, string> | undefined = {}, RequestBody = unknown, Query = unknown, Responses extends GenericResponse = never> = (request: Request<PathParams, unknown, RequestBody, Query, Record<string, unknown>>) => Promise<Responses | {
4
+ export type ApiEndpointHandler<PathParams extends Record<string, string> = {}, RequestBody = unknown, Query = unknown, Responses extends GenericResponse = never> = (request: Request<PathParams, unknown, RequestBody, Query, Record<string, unknown>>) => Promise<Responses | {
5
5
  code: (typeof HttpStatusCodes)["InternalServerError_500"];
6
6
  }>;
@@ -4,8 +4,8 @@ import { Prettify } from "../../utils/types";
4
4
  import { ApiEndpointHandler } from "./EndpointHandler";
5
5
  import { ExtractPathParams } from "./PathParameters";
6
6
  import { EmptyResponse, EmptyResponseSchema } from "./responses/emptyResponse";
7
- import { GenericResponseSchemaMap } from "./responses/index";
7
+ import { GenericResponse, GenericResponseSchemaMap } from "./responses/index";
8
8
  import { JsonResponseSchema, JsonResponseSchemaToResponseType } from "./responses/jsonResponse";
9
- export type HandlerForDefinition<Path extends string, RequestBody extends z.ZodType | undefined, Query extends z.ZodType | undefined, ResponsesMap extends GenericResponseSchemaMap> = ApiEndpointHandler<ExtractPathParams<Path>, RequestBody extends undefined ? undefined : z.infer<RequestBody>, Query extends undefined ? undefined : z.infer<Query>, Prettify<{
10
- [K in keyof ResponsesMap]: K extends HttpStatusCode ? ResponsesMap[K] extends JsonResponseSchema ? JsonResponseSchemaToResponseType<K, ResponsesMap[K]> : ResponsesMap[K] extends EmptyResponseSchema ? EmptyResponse<K> : never : never;
11
- }[keyof ResponsesMap]>>;
9
+ export type HandlerForDefinition<Path extends string, RequestBody extends z.ZodType | undefined, Query extends z.ZodType | undefined, ResponsesMap extends GenericResponseSchemaMap> = ApiEndpointHandler<ExtractPathParams<Path>, RequestBody extends undefined ? undefined : z.infer<RequestBody>, Query extends undefined ? undefined : z.infer<Query>, Exclude<Prettify<{
10
+ [K in keyof ResponsesMap]: K extends HttpStatusCode ? ResponsesMap[K] extends JsonResponseSchema ? JsonResponseSchemaToResponseType<K, ResponsesMap[K]> : ResponsesMap[K] extends EmptyResponseSchema ? EmptyResponse<K> : ResponsesMap[K] extends undefined ? never : GenericResponse : never;
11
+ }[keyof ResponsesMap]>, undefined>>;
@@ -2,4 +2,4 @@ export type ExtractPathParams<Path extends string> = Path extends `${string}:${i
2
2
  [K in Param | keyof ExtractPathParams<Rest>]: string;
3
3
  } : Path extends `${string}:${infer Param}` ? {
4
4
  [K in Param]: string;
5
- } : undefined;
5
+ } : {};
@@ -1,12 +1,19 @@
1
1
  import z from "zod";
2
2
  import { HttpMethod } from "../../constants/HttpMethods";
3
+ import { Prettify } from "../../utils/types";
3
4
  import { ApiEndpointDefinition } from "./EndpointDefinition";
4
5
  import { ApiEndpointHandler } from "./EndpointHandler";
5
6
  import { HandlerForDefinition } from "./HandlerFromDefinition";
6
- import { GenericResponseSchemaMap } from "./responses";
7
- export declare function createApiEndpointHandler<const ResponsesMap extends GenericResponseSchemaMap, const Path extends string, const Method extends HttpMethod, const RequestBody extends z.ZodType | undefined = undefined, const Query extends z.ZodType | undefined = undefined>(definition: ApiEndpointDefinition<Path, Method, RequestBody, Query, ResponsesMap>, handler: HandlerForDefinition<Path, RequestBody, Query, ResponsesMap>): {
8
- type: string;
9
- definition: ApiEndpointDefinition<Path, Method, RequestBody, Query, ResponsesMap>;
7
+ import { GenericResponse, GenericResponseSchemaMap } from "./responses";
8
+ export declare function createApiEndpointHandler<const ResponsesMap extends GenericResponseSchemaMap, const Path extends string, const Method extends HttpMethod, const RequestBody extends z.ZodType | undefined = undefined, const Query extends z.ZodType | undefined = undefined>(definition: Prettify<ApiEndpointDefinition<Path, Method, RequestBody, Query, ResponsesMap>>, handler: HandlerForDefinition<Path, RequestBody, Query, ResponsesMap>): {
9
+ definition: {
10
+ meta: import("./EndpointDefinition").ApiEndpointMeta;
11
+ path: Path;
12
+ method: Method;
13
+ requestBodySchema?: RequestBody | undefined;
14
+ querySchema?: Query | undefined;
15
+ responseSchemas: ResponsesMap;
16
+ };
10
17
  handler: HandlerForDefinition<Path, RequestBody, Query, ResponsesMap>;
11
18
  };
12
- export declare function buildApiEndpointHandler(handler: ApiEndpointHandler): import("express").RequestHandler<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
19
+ export declare function buildApiEndpointHandler<Handler extends ApiEndpointHandler<Record<string, string>, unknown, unknown, GenericResponse>>(handler: Handler): import("express").RequestHandler<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
@@ -2,7 +2,6 @@ import expressAsyncHandler from "express-async-handler";
2
2
  import { isJsonResponse } from "./responses/jsonResponse";
3
3
  export function createApiEndpointHandler(definition, handler) {
4
4
  return {
5
- type: "__API_ENDPOINT_DEFINITION__",
6
5
  definition,
7
6
  handler,
8
7
  };
@@ -0,0 +1,33 @@
1
+ import { describe, it } from "vitest";
2
+ import { createServer } from "../../server";
3
+ import { createApiEndpointHandler } from "./createApiHandler";
4
+ import testRequest from "supertest";
5
+ import z from "zod";
6
+ describe("createApiHandler", () => {
7
+ it("can create an API handler", () => {
8
+ const endpoint = createApiEndpointHandler({
9
+ meta: {
10
+ name: "",
11
+ description: "",
12
+ group: "",
13
+ },
14
+ method: "get",
15
+ path: "/test",
16
+ requestBodySchema: z.string(),
17
+ responseSchemas: {
18
+ 200: {},
19
+ },
20
+ }, async () => {
21
+ return {
22
+ code: 200,
23
+ };
24
+ });
25
+ const server = createServer({
26
+ inDevMode: true,
27
+ port: 3000,
28
+ logger: false,
29
+ });
30
+ server.registerApiEndpoint(endpoint);
31
+ testRequest(server.expressApp).get("/test").expect(200);
32
+ });
33
+ });
@@ -1,22 +1,20 @@
1
1
  import { Application } from "express";
2
- import z from "zod";
3
- import { HttpMethod } from "./constants/HttpMethods";
4
2
  import { ApiEndpointDefinition } from "./handlers/api/EndpointDefinition";
5
- import { ApiEndpointHandler } from "./handlers/api/EndpointHandler";
3
+ import { HandlerForDefinition } from "./handlers/api/HandlerFromDefinition";
6
4
  import { Logger } from "./utils/logging";
7
5
  export interface ServerConfig {
8
6
  inDevMode: boolean;
9
7
  port: number;
10
8
  logger: Logger | boolean;
11
- endpoints: Array<{
12
- endpointHandler: ApiEndpointHandler;
13
- endpointDefinition: ApiEndpointDefinition<string, HttpMethod, z.ZodType, z.ZodType, {}>;
14
- }>;
15
9
  }
16
10
  export interface Server {
17
11
  expressApp: Application;
18
12
  logger: Logger | boolean;
19
- endpointDefinitions: ApiEndpointDefinition<string, HttpMethod, z.ZodType, z.ZodType, {}>[];
13
+ endpointDefinitions: ApiEndpointDefinition[];
14
+ registerApiEndpoint<Definition extends ApiEndpointDefinition>({ definition, handler, }: {
15
+ definition: Definition;
16
+ handler: HandlerForDefinition<Definition["path"], Definition["requestBodySchema"], Definition["querySchema"], Definition["responseSchemas"]>;
17
+ }): void;
20
18
  start: () => void;
21
19
  }
22
20
  export declare function createServer(config: ServerConfig): Server;
@@ -5,20 +5,21 @@ import { buildRequestLogger, buildResponseLogger } from "./middleware/logging";
5
5
  import { buildBodyValidatorMiddleware, buildQueryValidatorMiddleware, } from "./middleware/validation";
6
6
  import { NoOpLogger } from "./utils/logging";
7
7
  import { hasNoValue, hasValue } from "./utils/typeGuards";
8
- function registerApiEndpoint(expressApp, endpointDefinition, endpointHandler) {
8
+ function registerApiEndpoint(expressApp, endpoint) {
9
+ const { definition, handler } = endpoint;
9
10
  const handlerStack = [
10
- hasValue(endpointDefinition.querySchema)
11
- ? buildQueryValidatorMiddleware(endpointDefinition.querySchema)
11
+ hasValue(definition.querySchema)
12
+ ? buildQueryValidatorMiddleware(definition.querySchema)
12
13
  : null,
13
- hasValue(endpointDefinition.requestBodySchema)
14
- ? buildBodyValidatorMiddleware(endpointDefinition.requestBodySchema)
14
+ hasValue(definition.requestBodySchema)
15
+ ? buildBodyValidatorMiddleware(definition.requestBodySchema)
15
16
  : null,
16
- buildApiEndpointHandler(endpointHandler),
17
+ buildApiEndpointHandler(handler),
17
18
  ].filter(hasValue);
18
- expressApp[endpointDefinition.method](endpointDefinition.path, handlerStack);
19
+ expressApp[definition.method](definition.path, handlerStack);
19
20
  }
20
21
  export function createServer(config) {
21
- const { port, inDevMode, endpoints } = config;
22
+ const { port, inDevMode } = config;
22
23
  const logger = config.logger === true
23
24
  ? console
24
25
  : config.logger === false || hasNoValue(config.logger)
@@ -30,14 +31,14 @@ export function createServer(config) {
30
31
  app.use(cookieParser());
31
32
  app.use(buildRequestLogger(logger, inDevMode));
32
33
  app.use(buildResponseLogger(logger, inDevMode));
33
- endpoints.forEach(({ endpointDefinition, endpointHandler }) => {
34
- registerApiEndpoint(app, endpointDefinition, endpointHandler);
35
- });
36
34
  return {
37
35
  expressApp: app,
38
36
  logger: logger,
39
- endpointDefinitions: endpoints.map((e) => e.endpointDefinition),
40
- start: () => {
37
+ endpointDefinitions: [],
38
+ registerApiEndpoint(endpoint) {
39
+ registerApiEndpoint(app, endpoint);
40
+ },
41
+ start() {
41
42
  app.listen(port);
42
43
  },
43
44
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "transit-kit",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "A declarative TypeScript framework for building type-safe Express.js APIs with automatic OpenAPI generation",
5
5
  "keywords": [
6
6
  "express",
@@ -28,9 +28,9 @@
28
28
  ],
29
29
  "exports": {
30
30
  "./server": {
31
+ "types": "./dist/server/server.d.ts",
31
32
  "import": "./dist/server/index.js",
32
- "require": "./dist/server/index.js",
33
- "types": "./dist/server/server.d.ts"
33
+ "require": "./dist/server/index.js"
34
34
  }
35
35
  },
36
36
  "bin": "./dist/cli/cli.js",
@@ -42,6 +42,7 @@
42
42
  "devDependencies": {
43
43
  "@types/cookie-parser": "^1.4.9",
44
44
  "@types/express": "^5.0.0",
45
+ "@types/supertest": "^6.0.3",
45
46
  "@vitest/coverage-v8": "^4.0.15",
46
47
  "@vitest/eslint-plugin": "^1.5.2",
47
48
  "eslint": "^9.39.1",
@@ -49,6 +50,7 @@
49
50
  "eslint-plugin-prettier": "^5.5.4",
50
51
  "jiti": "^2.6.1",
51
52
  "prettier": "^3.7.4",
53
+ "supertest": "^7.1.4",
52
54
  "tslib": "2.8.1",
53
55
  "typescript": "^5.9.3",
54
56
  "typescript-eslint": "^8.49.0",