transit-kit 0.7.0 → 0.8.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.
Files changed (34) hide show
  1. package/dist/generator/generateOpenApi.d.ts +8 -4
  2. package/dist/generator/generateOpenApi.js +6 -2
  3. package/dist/generator/index.d.ts +1 -1
  4. package/dist/generator/index.js +1 -1
  5. package/dist/server/handlers/api/ApiEndpoint.d.ts +4 -4
  6. package/dist/server/handlers/api/EndpointDefinition.d.ts +3 -3
  7. package/dist/server/handlers/api/EndpointHandler.d.ts +2 -2
  8. package/dist/server/handlers/api/HandlerFromDefinition.d.ts +6 -6
  9. package/dist/server/handlers/api/createApiHandler.d.ts +9 -9
  10. package/dist/server/handlers/api/responses/index.d.ts +2 -2
  11. package/dist/server/handlers/api/responses/jsonResponse.d.ts +1 -1
  12. package/dist/server/index.d.ts +6 -4
  13. package/dist/server/index.js +6 -4
  14. package/dist/server/middleware/auth.d.ts +1 -1
  15. package/dist/server/middleware/auth.js +2 -2
  16. package/dist/server/middleware/logging.d.ts +1 -1
  17. package/dist/server/middleware/logging.js +1 -1
  18. package/dist/server/middleware/validation.js +1 -1
  19. package/dist/server/security/SecuritySchema.d.ts +2 -2
  20. package/dist/server/security/SecuritySchema.js +2 -2
  21. package/dist/server/security/basicAuth.js +1 -1
  22. package/dist/server/server.d.ts +3 -3
  23. package/dist/server/server.js +7 -7
  24. package/package.json +2 -2
  25. package/dist/generator/generateOpenApi.spec.d.ts +0 -1
  26. package/dist/generator/generateOpenApi.spec.js +0 -66
  27. package/dist/server/handlers/api/HandlerFromDefinition.spec.d.ts +0 -1
  28. package/dist/server/handlers/api/HandlerFromDefinition.spec.js +0 -15
  29. package/dist/server/handlers/api/PathParameters.spec.d.ts +0 -1
  30. package/dist/server/handlers/api/PathParameters.spec.js +0 -12
  31. package/dist/server/handlers/api/createApiHandler.spec.d.ts +0 -17
  32. package/dist/server/handlers/api/createApiHandler.spec.js +0 -73
  33. package/dist/server/security/basicAuth.spec.d.ts +0 -1
  34. package/dist/server/security/basicAuth.spec.js +0 -46
@@ -1,13 +1,17 @@
1
- import { HttpMethod } from "../server/constants/HttpMethods";
2
- import { ApiEndpointDefinition } from "../server/handlers/api/EndpointDefinition";
3
- import { GenericResponseSchemaMap } from "../server/handlers/api/responses";
1
+ import { HttpMethod } from "../server/constants/HttpMethods.js";
2
+ import { ApiEndpointDefinition } from "../server/handlers/api/EndpointDefinition.js";
3
+ import { GenericResponseSchemaMap } from "../server/handlers/api/responses/index.js";
4
4
  import { ZodType } from "zod";
5
5
  import { OpenAPIV3 } from "openapi-types";
6
- import { Server } from "../server";
6
+ import { Server } from "../server/server.js";
7
7
  declare function translateToOpenAPIPathItem(definition: ApiEndpointDefinition<string, HttpMethod, ZodType | undefined, ZodType | undefined, GenericResponseSchemaMap>): [string, OpenAPIV3.PathItemObject];
8
8
  interface GeneratorOptions {
9
9
  title: string;
10
10
  version: string;
11
+ description?: string;
12
+ servers?: OpenAPIV3.ServerObject[];
13
+ contact?: OpenAPIV3.ContactObject;
14
+ license?: OpenAPIV3.LicenseObject;
11
15
  }
12
16
  export declare function generateOpenApiDoc(server: Server, options: GeneratorOptions): Promise<OpenAPIV3.Document>;
13
17
  export declare const __TEST_EXPORTS: {
@@ -1,6 +1,6 @@
1
1
  import z from "zod";
2
- import { hasValue } from "../server/utils/typeGuards";
3
- import { isJsonResponseSchema } from "../server/handlers/api/responses/jsonResponse";
2
+ import { hasValue } from "../server/utils/typeGuards.js";
3
+ import { isJsonResponseSchema } from "../server/handlers/api/responses/jsonResponse.js";
4
4
  function extractPathAndParameters(path) {
5
5
  const parameters = path.match(/:([a-zA-Z0-9_]+)/g)?.map((param) => {
6
6
  return {
@@ -155,7 +155,11 @@ export async function generateOpenApiDoc(server, options) {
155
155
  info: {
156
156
  title: options.title,
157
157
  version: options.version,
158
+ description: options.description,
159
+ license: options.license,
160
+ contact: options.contact,
158
161
  },
162
+ servers: options.servers ?? [],
159
163
  paths: paths,
160
164
  components: {
161
165
  securitySchemes,
@@ -1 +1 @@
1
- export { generateOpenApiDoc } from "./generateOpenApi";
1
+ export { generateOpenApiDoc } from "./generateOpenApi.js";
@@ -1 +1 @@
1
- export { generateOpenApiDoc } from "./generateOpenApi";
1
+ export { generateOpenApiDoc } from "./generateOpenApi.js";
@@ -1,8 +1,8 @@
1
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";
2
+ import { HttpMethod } from "../../constants/HttpMethods.js";
3
+ import { ApiEndpointDefinition } from "./EndpointDefinition.js";
4
+ import { HandlerForDefinition } from "./HandlerFromDefinition.js";
5
+ import { GenericResponseSchemaMap } from "./responses/index.js";
6
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
7
  definition: ApiEndpointDefinition<Path, Method, RequestBody, Query, ResponseMap>;
8
8
  handler: Handler;
@@ -1,7 +1,7 @@
1
1
  import z from "zod";
2
- import { HttpMethod } from "../../constants/HttpMethods";
3
- import { SecurityScheme } from "../../security/SecuritySchema";
4
- import { GenericResponseSchemaMap } from "./responses/index";
2
+ import { HttpMethod } from "../../constants/HttpMethods.js";
3
+ import { SecurityScheme } from "../../security/SecuritySchema.js";
4
+ import { GenericResponseSchemaMap } from "./responses/index.js";
5
5
  export interface ApiEndpointMeta {
6
6
  name: string;
7
7
  group: string;
@@ -1,6 +1,6 @@
1
1
  import { Request, Response } from "express";
2
- import { HttpStatusCode } from "../../constants/HttpStatusCodes";
3
- import { HandlerResponse } from "./responses";
2
+ import { HttpStatusCode } from "../../constants/HttpStatusCodes.js";
3
+ import { HandlerResponse } from "./responses/index.js";
4
4
  export type ApiEndpointHandler<Responses extends HandlerResponse<HttpStatusCode, unknown>, PathParams extends Record<string, string> = {}, RequestBody = unknown, Query = unknown, Caller = unknown> = (typedRequestData: {
5
5
  request: Request<PathParams, unknown, RequestBody, Query, Record<string, unknown>>;
6
6
  response: Response<unknown>;
@@ -1,10 +1,10 @@
1
1
  import z from "zod";
2
- import { HttpStatusCode } from "../../constants/HttpStatusCodes";
3
- import { SecurityScheme } from "../../security/SecuritySchema";
4
- import { Prettify } from "../../utils/types";
5
- import { ApiEndpointHandler } from "./EndpointHandler";
6
- import { ExtractPathParams } from "./PathParameters";
7
- import { GenericResponseSchema, GenericResponseSchemaMap, InferResponseFromSchema } from "./responses/index";
2
+ import { HttpStatusCode } from "../../constants/HttpStatusCodes.js";
3
+ import { SecurityScheme } from "../../security/SecuritySchema.js";
4
+ import { Prettify } from "../../utils/types.js";
5
+ import { ApiEndpointHandler } from "./EndpointHandler.js";
6
+ import { ExtractPathParams } from "./PathParameters.js";
7
+ import { GenericResponseSchema, GenericResponseSchemaMap, InferResponseFromSchema } from "./responses/index.js";
8
8
  export type HandlerForDefinition<Path extends string, RequestBody extends z.ZodType | undefined, Query extends z.ZodType | undefined, ResponsesMap extends GenericResponseSchemaMap, SecuritySchemas extends SecurityScheme<unknown>[] = []> = ApiEndpointHandler<Exclude<Prettify<{
9
9
  [K in keyof ResponsesMap]: K extends HttpStatusCode ? InferResponseFromSchema<K, ResponsesMap[K] extends GenericResponseSchema ? ResponsesMap[K] : never> : never;
10
10
  }[keyof ResponsesMap]>, undefined>, ExtractPathParams<Path>, RequestBody extends undefined ? undefined : z.infer<RequestBody>, Query extends undefined ? undefined : z.infer<Query>, SecuritySchemas extends SecurityScheme<infer Caller>[] ? Caller : unknown>;
@@ -1,15 +1,15 @@
1
1
  import z from "zod";
2
- import { HttpMethod } from "../../constants/HttpMethods";
3
- import { HttpStatusCode } from "../../constants/HttpStatusCodes";
4
- import { SecurityScheme } from "../../security/SecuritySchema";
5
- import { Prettify } from "../../utils/types";
6
- import { ApiEndpointDefinition } from "./EndpointDefinition";
7
- import { ApiEndpointHandler } from "./EndpointHandler";
8
- import { HandlerForDefinition } from "./HandlerFromDefinition";
9
- import { GenericResponseSchemaMap, HandlerResponse } from "./responses";
2
+ import { HttpMethod } from "../../constants/HttpMethods.js";
3
+ import { HttpStatusCode } from "../../constants/HttpStatusCodes.js";
4
+ import { SecurityScheme } from "../../security/SecuritySchema.js";
5
+ import { Prettify } from "../../utils/types.js";
6
+ import { ApiEndpointDefinition } from "./EndpointDefinition.js";
7
+ import { ApiEndpointHandler } from "./EndpointHandler.js";
8
+ import { HandlerForDefinition } from "./HandlerFromDefinition.js";
9
+ import { GenericResponseSchemaMap, HandlerResponse } from "./responses/index.js";
10
10
  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, const SecuritySchemas extends SecurityScheme<unknown>[] = []>(definition: Prettify<ApiEndpointDefinition<Path, Method, RequestBody, Query, ResponsesMap, SecuritySchemas>>, handler: HandlerForDefinition<Path, RequestBody, Query, ResponsesMap, SecuritySchemas>): {
11
11
  definition: {
12
- meta: import("./EndpointDefinition").ApiEndpointMeta;
12
+ meta: import("./EndpointDefinition.js").ApiEndpointMeta;
13
13
  path: Path;
14
14
  method: Method;
15
15
  requestBodySchema?: RequestBody | undefined;
@@ -1,6 +1,6 @@
1
1
  import z from "zod";
2
- import { HttpStatusCode } from "../../../constants/HttpStatusCodes";
3
- import { JsonResponseSchema } from "./jsonResponse";
2
+ import { HttpStatusCode } from "../../../constants/HttpStatusCodes.js";
3
+ import { JsonResponseSchema } from "./jsonResponse.js";
4
4
  export type AbstractResponseSchema<Headers extends string[] | undefined = string[] | undefined> = {
5
5
  type: string;
6
6
  headers?: Headers;
@@ -1,5 +1,5 @@
1
1
  import z from "zod";
2
- import { AbstractResponseSchema } from ".";
2
+ import { AbstractResponseSchema } from "./index.js";
3
3
  export interface JsonResponseSchema<DataSchema extends z.ZodType = z.ZodType, Headers extends string[] | undefined = string[] | undefined> extends AbstractResponseSchema<Headers> {
4
4
  type: "json";
5
5
  schema: DataSchema;
@@ -1,6 +1,8 @@
1
- export { createApiEndpointHandler } from "./handlers/api/createApiHandler";
2
- export { createBasicAuthSchema } from "./security/basicAuth";
3
- export { createBearerAuthSchema } from "./security/bearerAuth";
4
- export { createServer, type Server, type ServerConfig } from "./server";
1
+ export { HttpStatusCodes, type HttpStatusCode, } from "./constants/HttpStatusCodes.js";
2
+ export { HttpMethods, type HttpMethod } from "./constants/HttpMethods.js";
3
+ export { createApiEndpointHandler } from "./handlers/api/createApiHandler.js";
4
+ export { createBasicAuthSchema } from "./security/basicAuth.js";
5
+ export { createBearerAuthSchema } from "./security/bearerAuth.js";
6
+ export { createServer, type Server, type ServerConfig } from "./server.js";
5
7
  declare const _default: {};
6
8
  export default _default;
@@ -1,5 +1,7 @@
1
- export { createApiEndpointHandler } from "./handlers/api/createApiHandler";
2
- export { createBasicAuthSchema } from "./security/basicAuth";
3
- export { createBearerAuthSchema } from "./security/bearerAuth";
4
- export { createServer } from "./server";
1
+ export { HttpStatusCodes, } from "./constants/HttpStatusCodes.js";
2
+ export { HttpMethods } from "./constants/HttpMethods.js";
3
+ export { createApiEndpointHandler } from "./handlers/api/createApiHandler.js";
4
+ export { createBasicAuthSchema } from "./security/basicAuth.js";
5
+ export { createBearerAuthSchema } from "./security/bearerAuth.js";
6
+ export { createServer } from "./server.js";
5
7
  export default {};
@@ -1,2 +1,2 @@
1
- import { SecurityScheme } from "../security/SecuritySchema";
1
+ import { SecurityScheme } from "../security/SecuritySchema.js";
2
2
  export declare function buildAuthenticationMiddleware<Caller>(schemes: SecurityScheme<Caller>[]): import("express").RequestHandler<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
@@ -1,6 +1,6 @@
1
1
  import expressAsyncHandler from "express-async-handler";
2
- import { HttpStatusCodes } from "../constants/HttpStatusCodes";
3
- import { authenticate } from "../security/SecuritySchema";
2
+ import { HttpStatusCodes } from "../constants/HttpStatusCodes.js";
3
+ import { authenticate } from "../security/SecuritySchema.js";
4
4
  export function buildAuthenticationMiddleware(schemes) {
5
5
  return expressAsyncHandler(async (request, response, next) => {
6
6
  const caller = await authenticate(schemes, request);
@@ -1,4 +1,4 @@
1
1
  import { NextFunction, Request, Response } from "express";
2
- import { Logger } from "../utils/logging";
2
+ import { Logger } from "../utils/logging.js";
3
3
  export declare function buildRequestLogger(logger: Logger, isInDevMode: boolean): (req: Request, res: Response, next: NextFunction) => void;
4
4
  export declare function buildResponseLogger(logger: Logger, isInDevMode: boolean): (req: Request, res: Response, next: NextFunction) => void;
@@ -1,4 +1,4 @@
1
- import colors from "colors/safe";
1
+ import colors from "colors/safe.js";
2
2
  export function buildRequestLogger(logger, isInDevMode) {
3
3
  return (req, res, next) => {
4
4
  logger.info(`[Request] ${colors.cyan(req.method)} - ${colors.cyan(req.path)}`);
@@ -1,4 +1,4 @@
1
- import { HttpStatusCodes } from "../constants/HttpStatusCodes";
1
+ import { HttpStatusCodes } from "../constants/HttpStatusCodes.js";
2
2
  export function buildBodyValidatorMiddleware(schema) {
3
3
  return (request, response, next) => {
4
4
  const validationResult = schema.safeParse(request.body);
@@ -1,5 +1,5 @@
1
1
  import { Request } from "express";
2
- import { BasicAuthScheme } from "./basicAuth";
3
- import { BearerAuthScheme } from "./bearerAuth";
2
+ import { BasicAuthScheme } from "./basicAuth.js";
3
+ import { BearerAuthScheme } from "./bearerAuth.js";
4
4
  export type SecurityScheme<Caller> = BasicAuthScheme<Caller> | BearerAuthScheme<Caller>;
5
5
  export declare function authenticate<Caller>(schemes: SecurityScheme<Caller>[], request: Request): Promise<Caller | null>;
@@ -1,5 +1,5 @@
1
- import { buildBasicAuthenticator } from "./basicAuth";
2
- import { buildBearerAuthenticator } from "./bearerAuth";
1
+ import { buildBasicAuthenticator } from "./basicAuth.js";
2
+ import { buildBearerAuthenticator } from "./bearerAuth.js";
3
3
  export async function authenticate(schemes, request) {
4
4
  const authenticationResults = await Promise.all(schemes.map((scheme) => {
5
5
  switch (scheme.scheme) {
@@ -1,4 +1,4 @@
1
- import { hasNoValue } from "../utils/typeGuards";
1
+ import { hasNoValue } from "../utils/typeGuards.js";
2
2
  export function createBasicAuthSchema(name, validateCaller) {
3
3
  return {
4
4
  name,
@@ -1,7 +1,7 @@
1
1
  import { Application } from "express";
2
- import { ApiEndpointDefinition } from "./handlers/api/EndpointDefinition";
3
- import { HandlerForDefinition } from "./handlers/api/HandlerFromDefinition";
4
- import { Logger } from "./utils/logging";
2
+ import { ApiEndpointDefinition } from "./handlers/api/EndpointDefinition.js";
3
+ import { HandlerForDefinition } from "./handlers/api/HandlerFromDefinition.js";
4
+ import { Logger } from "./utils/logging.js";
5
5
  export interface ServerConfig {
6
6
  inDevMode: boolean;
7
7
  port: number;
@@ -1,12 +1,12 @@
1
1
  import cookieParser from "cookie-parser";
2
2
  import express from "express";
3
- import { buildApiEndpointHandler } from "./handlers/api/createApiHandler";
4
- import { buildAuthenticationMiddleware } from "./middleware/auth";
5
- import { buildRequestLogger, buildResponseLogger } from "./middleware/logging";
6
- import { buildBodyValidatorMiddleware, buildQueryValidatorMiddleware, } from "./middleware/validation";
7
- import { isEmpty } from "./utils/funcs";
8
- import { NoOpLogger } from "./utils/logging";
9
- import { hasNoValue, hasValue } from "./utils/typeGuards";
3
+ import { buildApiEndpointHandler } from "./handlers/api/createApiHandler.js";
4
+ import { buildAuthenticationMiddleware } from "./middleware/auth.js";
5
+ import { buildRequestLogger, buildResponseLogger, } from "./middleware/logging.js";
6
+ import { buildBodyValidatorMiddleware, buildQueryValidatorMiddleware, } from "./middleware/validation.js";
7
+ import { isEmpty } from "./utils/funcs.js";
8
+ import { NoOpLogger } from "./utils/logging.js";
9
+ import { hasNoValue, hasValue } from "./utils/typeGuards.js";
10
10
  function registerApiEndpoint(expressApp, endpoint) {
11
11
  const { definition, handler } = endpoint;
12
12
  const handlerStack = [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "transit-kit",
3
- "version": "0.7.0",
3
+ "version": "0.8.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",
@@ -41,7 +41,7 @@
41
41
  "scripts": {
42
42
  "lint": "eslint",
43
43
  "test": "vitest",
44
- "build": "rm -rf ./dist && tsc"
44
+ "build": "rm -rf ./dist && tsc -p ./tsconfig.build.json"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/cookie-parser": "^1.4.9",
@@ -1 +0,0 @@
1
- export {};
@@ -1,66 +0,0 @@
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
- securitySchemes: [],
17
- responseSchemas: {
18
- 200: {
19
- type: "json",
20
- schema: z.string(),
21
- },
22
- },
23
- }, async ({ request }) => {
24
- return {
25
- code: 200,
26
- data: request.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
- security: [],
51
- responses: {
52
- "200": {
53
- description: "Response for status code 200",
54
- content: {
55
- "application/json": {
56
- schema: expectedSchema,
57
- },
58
- },
59
- },
60
- },
61
- },
62
- };
63
- expect(path).toBe(expectedPath);
64
- expect(pathItem).toEqual(expectedPathItem);
65
- });
66
- });
@@ -1,15 +0,0 @@
1
- import { describe, expectTypeOf, it } from "vitest";
2
- describe("HandlerFromDefinition", () => {
3
- it("can infer handler responses correctly (Json)", () => {
4
- expectTypeOf().toEqualTypeOf();
5
- });
6
- it("can infer handler responses correctly (headers)", () => {
7
- expectTypeOf().toEqualTypeOf();
8
- });
9
- it("can infer caller from auth schema (Basic)", () => {
10
- expectTypeOf().toEqualTypeOf();
11
- });
12
- it("can infer caller from auth schema (Bearer)", () => {
13
- expectTypeOf().toEqualTypeOf();
14
- });
15
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,12 +0,0 @@
1
- import { describe, expectTypeOf, it } from "vitest";
2
- describe("ExtractPathParameters", () => {
3
- it("can infer the parameter types of a path", () => {
4
- expectTypeOf().toEqualTypeOf();
5
- });
6
- it("can infer multiple params", () => {
7
- expectTypeOf().toEqualTypeOf();
8
- });
9
- it("can infer correctly if no param is present", () => {
10
- expectTypeOf().toEqualTypeOf();
11
- });
12
- });
@@ -1,17 +0,0 @@
1
- import z from "zod";
2
- export declare const testEndpointBase: {
3
- meta: {
4
- name: string;
5
- description: string;
6
- group: string;
7
- };
8
- method: "get";
9
- path: string;
10
- securitySchemes: never[];
11
- responseSchemas: {
12
- 200: {
13
- type: "json";
14
- schema: z.ZodString;
15
- };
16
- };
17
- };
@@ -1,73 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { createServer } from "../../server";
3
- import { createApiEndpointHandler } from "./createApiHandler";
4
- import testRequest from "supertest";
5
- import z from "zod";
6
- import { HttpMethods } from "../../constants/HttpMethods";
7
- export const testEndpointBase = {
8
- meta: {
9
- name: "getTest",
10
- description: "Gets test element",
11
- group: "test",
12
- },
13
- method: HttpMethods.get,
14
- path: "/test",
15
- securitySchemes: [],
16
- responseSchemas: {
17
- 200: {
18
- type: "json",
19
- schema: z.string(),
20
- },
21
- },
22
- };
23
- describe("createApiHandler", () => {
24
- it("can create an API handler that responds correctly (json)", async () => {
25
- const endpoint = createApiEndpointHandler({
26
- ...testEndpointBase,
27
- }, async () => {
28
- return {
29
- code: 200,
30
- data: "test",
31
- };
32
- });
33
- const server = createServer({
34
- inDevMode: true,
35
- port: 3000,
36
- logger: false,
37
- });
38
- server.registerApiEndpoint(endpoint);
39
- const response = await testRequest(server.expressApp).get("/test");
40
- expect(response.status).toBe(200);
41
- expect(response.text).toBe("test");
42
- });
43
- it("can create an API handler that responds with custom headers", async () => {
44
- const endpoint = createApiEndpointHandler({
45
- ...testEndpointBase,
46
- responseSchemas: {
47
- 200: {
48
- type: "json",
49
- schema: z.string(),
50
- headers: ["X-Custom-Header"],
51
- },
52
- },
53
- }, async () => {
54
- return {
55
- code: 200,
56
- data: "test",
57
- headers: {
58
- "X-Custom-Header": "CustomValue",
59
- },
60
- };
61
- });
62
- const server = createServer({
63
- inDevMode: true,
64
- port: 3000,
65
- logger: false,
66
- });
67
- server.registerApiEndpoint(endpoint);
68
- const response = await testRequest(server.expressApp).get("/test");
69
- expect(response.status).toBe(200);
70
- expect(response.text).toBe("test");
71
- expect(response.headers["x-custom-header"]).toBe("CustomValue");
72
- });
73
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,46 +0,0 @@
1
- import testRequest from "supertest";
2
- import { describe, expect, it } from "vitest";
3
- import { HttpStatusCodes } from "../constants/HttpStatusCodes";
4
- import { createApiEndpointHandler } from "../handlers/api/createApiHandler";
5
- import { testEndpointBase } from "../handlers/api/createApiHandler.spec";
6
- import { createServer } from "../server";
7
- import { createBasicAuthSchema } from "./basicAuth";
8
- describe("basic auth schema", () => {
9
- const testUsername = "Test";
10
- const testPassword = "TestPW";
11
- const encodedCredentials = Buffer.from(`${testUsername}:${testPassword}`).toString("base64");
12
- const authScheme = createBasicAuthSchema("TestAuth", async (name, password) => {
13
- if (name === testUsername && password === testPassword) {
14
- return {
15
- username: name,
16
- };
17
- }
18
- else {
19
- return null;
20
- }
21
- });
22
- const endpoint = createApiEndpointHandler({
23
- ...testEndpointBase,
24
- securitySchemes: [authScheme],
25
- }, async () => {
26
- return { code: HttpStatusCodes.Ok_200, data: "test" };
27
- });
28
- const server = createServer({
29
- port: 3000,
30
- inDevMode: false,
31
- logger: false,
32
- });
33
- server.registerApiEndpoint(endpoint);
34
- it("accepts valid credentials", async () => {
35
- const response = await testRequest(server.expressApp)
36
- .get("/test")
37
- .set("Authorization", `Basic ${encodedCredentials}`);
38
- expect(response.status).toBe(HttpStatusCodes.Ok_200);
39
- });
40
- it("rejects invalid credentials", async () => {
41
- const response = await testRequest(server.expressApp)
42
- .get("/test")
43
- .set("Authorization", `Basic INVALID:INVALID`);
44
- expect(response.status).toBe(HttpStatusCodes.Unauthorized_401);
45
- });
46
- });