### TypeScript: API Creation Source: https://github.com/yourtion/node-erest/blob/main/src/test/QUICK_REFERENCE.md Provides examples of creating API endpoints using helper functions. Demonstrates creating a simple GET API and a POST API with a request body and required fields. ```typescript // Simple API const api = createGetApi(apiService.api, "/users", "Get Users"); // API with parameters const api = createPostApi(apiService.api, "/users", "Create User") .body({ name: commonParams.name, age: commonParams.age }) .required(["name"]); ``` -------------------------------- ### Test Setup Utilities Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Utilities for setting up and tearing down test environments, including creating test ERest instances, setting up Express or Koa test environments, and cleaning up resources. ```TypeScript const apiService = createTestERestInstance(options?); const { app, server } = setupExpressTest(apiService); const { app, server } = setupKoaTest(apiService); cleanupTestEnvironment(server); ``` -------------------------------- ### TypeScript: Basic Test Setup Source: https://github.com/yourtion/node-erest/blob/main/src/test/QUICK_REFERENCE.md Sets up a basic test environment by creating an instance of the test Erest service and importing helper functions for assertions and API creation. ```typescript import { createTestERestInstance } from "./utils/test-setup"; import { assertParamValidation, assertSchemaValidation } from "./utils/assertion-helpers"; import { createGetApi, commonParams } from "./utils/api-helpers"; // Basic test setup const apiService = createTestERestInstance(); const api = apiService.api; ``` -------------------------------- ### Install ERest using npm, yarn, or pnpm Source: https://github.com/yourtion/node-erest/blob/main/README.md This snippet shows how to install the ERest package using different package managers: npm, yarn, and pnpm. It's the first step to using ERest in your project. ```bash # npm npm install erest # yarn yarn add erest # pnpm pnpm add erest ``` -------------------------------- ### API Fixtures for Testing Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Defines standardized API configuration data for testing purposes. Includes examples for basic GET and complex POST API configurations with properties like method, path, title, body, and required fields. ```typescript export const apiFixtures = { basicGetApi: { method: "get", path: "/test", title: "Test API", group: "Test" }, complexPostApi: { method: "post", path: "/users", title: "Create User", body: { /* ... */ }, required: ["name", "email"] } }; ``` -------------------------------- ### API Integration Tests with ERest Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Sets up and runs API integration tests using ERest. It initializes an ERest instance and an Express application, performing setup before each test and cleanup after. ```typescript import { createTestERestInstance, setupExpressTest } from "./utils/test-setup"; describe("API Integration Tests", () => { let apiService, app, server; beforeEach(() => { apiService = createTestERestInstance(); ({ app, server } = setupExpressTest(apiService)); }); afterEach(() => { cleanupTestEnvironment(server); }); }); ``` -------------------------------- ### Basic ERest API Setup with Express Source: https://github.com/yourtion/node-erest/blob/main/README.md This TypeScript code demonstrates the basic setup of an ERest API integrated with an Express application. It includes defining API routes, specifying request parameters using Zod, and handling responses. ```typescript import ERest, { z } from 'erest'; import express from 'express'; // 创建 ERest 实例 const api = new ERest({ info: { title: 'My API', description: 'A powerful API built with ERest', version: new Date(), host: 'http://localhost:3000', basePath: '/api', }, groups: { user: '用户管理', post: '文章管理', }, }); // 定义 API 接口 api.api.get('/users/:id') .group('user') .title('获取用户信息') .params(z.object({ id: z.string().describe('用户ID'), })) .query(z.object({ include: z.string().optional().describe('包含的关联数据'), })) .register(async (req, res) => { const { id } = req.params; const { include } = req.query; // 业务逻辑 const user = await getUserById(id, include); res.json({ success: true, data: user }); }); // 绑定到 Express const app = express(); const router = express.Router(); app.use('/api', router); api.bindRouter(router, api.checkerExpress); app.listen(3000, () => { console.log('🚀 Server running on http://localhost:3000'); }); ``` -------------------------------- ### TypeScript: Test Structure Example Source: https://github.com/yourtion/node-erest/blob/main/src/test/QUICK_REFERENCE.md Illustrates a standard testing structure using `describe` and `test` blocks for organizing tests. Includes placeholders for setting up test data, executing logic, and making assertions. ```typescript describe("Component - Feature", () => { describe("Specific Functionality", () => { test("should handle specific case", () => { // Arrange const testData = /* setup */; // Act const result = /* execute */; // Assert assertSomething(result, expected); }); }); }); ``` -------------------------------- ### API Helpers for ERest Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Provides standardized functions for creating and managing API instances in tests using ERest. Includes functions for GET, POST, and all CRUD APIs, along with common parameter definitions. ```TypeScript const getApi = createGetApi(api, "/users", "Get Users"); const postApi = createPostApi(api, "/users", "Create User"); createAllCrudApis(api); const commonParams = { id: build(TYPES.String, "ID", true), name: build(TYPES.String, "Name", true), age: build(TYPES.Number, "Age", false), email: build(TYPES.String, "Email", false) }; ``` ```TypeScript import { createGetApi, commonParams } from "./utils/api-helpers"; test("should create user API", () => { const api = createTestERestInstance().api; const userApi = createGetApi(api, "/users/:id", "Get User") .params({ id: commonParams.id }) .query({ include: commonParams.name }); // API is now ready for testing }); ``` -------------------------------- ### TypeScript: Parameter Validation Source: https://github.com/yourtion/node-erest/blob/main/src/test/QUICK_REFERENCE.md Demonstrates how to use assertion helpers for validating parameters in tests. Includes examples for both successful parameter validation and handling validation errors. ```typescript // Success case assertParamValidation(paramsChecker, "name", "John", stringParam, "John"); // Error case assertParamValidation(paramsChecker, "name", null, stringParam, /required/); ``` -------------------------------- ### TypeScript: Schema Validation Source: https://github.com/yourtion/node-erest/blob/main/src/test/QUICK_REFERENCE.md Illustrates the use of assertion helpers for schema validation in tests. Shows examples for validating data against a schema for both valid and invalid cases. ```typescript // Valid data assertSchemaValidation(schemaChecker, validData, schema, expectedResult); // Invalid data assertSchemaValidation(schemaChecker, invalidData, schema, /error pattern/); ``` -------------------------------- ### TypeScript: Import Cheatsheet Source: https://github.com/yourtion/node-erest/blob/main/src/test/QUICK_REFERENCE.md A comprehensive cheatsheet for importing various utilities and helpers from different modules within the node-erest project, including test setup, assertions, API helpers, mocks, and fixtures. ```typescript // Test setup import { createTestERestInstance, setupExpressTest } from "./utils/test-setup"; // Assertions import { assertParamValidation, assertSchemaValidation, assertApiRegistered } from "./utils/assertion-helpers"; // API helpers import { createGetApi, createPostApi, commonParams } from "./utils/api-helpers"; // Mocks import { createMockHook, createStandardHooks } from "./utils/mock-factories"; // Fixtures import { apiFixtures, schemaFixtures } from "./fixtures"; ``` -------------------------------- ### Get Schema Manager Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Retrieves the schema manager, which provides methods for checking, creating, getting, and registering Zod schemas. It allows for managing schema definitions within the application. ```TypeScript get schema(): { check: (name: string, value: unknown) => boolean; createZodSchema: (schemaType: ISchemaType) => ZodType; get: ( name: string, ) => | undefined | ZodType>; has: (name: string) => boolean; register: (name: string, schema: ZodType) => void; } ``` -------------------------------- ### Type Safety in TypeScript Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Illustrates the importance of using TypeScript types consistently and avoiding `any` types in test code. It shows a type-safe example using `ISchemaType` and contrasts it with an untyped approach. ```typescript const param: ISchemaType = build(TYPES.String, "Name", true); const param = build(TYPES.String, "Name", true) as any; ``` -------------------------------- ### Get Test Instance Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Provides access to the API test instance. This allows for the execution and management of API tests within the Node-Erest framework. ```TypeScript get test(): IAPITest ``` -------------------------------- ### Schema Fixtures for Validation Testing Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Contains schema definitions and associated test data for validation testing. It includes examples of user schemas with type and required status, and test data for both valid and invalid user objects. ```typescript export const schemaFixtures = { userSchema: { name: { type: "String", required: true }, age: { type: "Number", required: false }, email: { type: "String", required: true } }, testData: { validUser: { name: "John", age: 30, email: "john@example.com" }, invalidUser: { name: "John" } // missing required email } }; ``` -------------------------------- ### ERest with Native Zod Type Support for Request Body Source: https://github.com/yourtion/node-erest/blob/main/README.md This TypeScript example showcases ERest's native Zod integration for defining and validating request bodies. It defines a complex user creation schema and demonstrates how ERest provides type-safe access to the request body. ```typescript import { z } from 'erest'; // 定义复杂的数据模型 const CreateUserSchema = z.object({ name: z.string().min(1).max(50), email: z.string().email(), age: z.number().int().min(18).max(120), tags: z.array(z.string()).optional(), profile: z.object({ bio: z.string().optional(), avatar: z.string().url().optional(), }).optional(), }); api.api.post('/users') .group('user') .title('创建用户') .body(CreateUserSchema) .register(async (req, res) => { // req.body 自动获得完整的类型推导 const userData = req.body; // 类型安全! const user = await createUser(userData); res.json({ success: true, data: user }); }); ``` -------------------------------- ### IGruop Interface Definition Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/IGruop.html Defines the IGruop interface, which is used for managing API endpoints. It includes methods for setting up middleware, defining API configurations, and performing CRUD operations (get, post, put, patch, delete). ```TypeScript interface IGruop { before: (...fn: T[]) => IGruop; define: (opt: APIDefine) => API; delete: (path: string) => API; get: (path: string) => API; middleware: (...fn: T[]) => IGruop; patch: (path: string) => API; post: (path: string) => API; put: (path: string) => API; [key: string]: unknown; } ``` -------------------------------- ### IApiInfo Interface Definition Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/IApiInfo.html Defines the IApiInfo interface for API interactions. It includes properties for managing API definitions, hooks, and documentation, along with methods for common HTTP operations like GET, POST, PUT, PATCH, and DELETE. ```TypeScript interface IApiInfo { $apis: Map>; afterHooks: Set; beforeHooks: Set; define: (opt: APIDefine) => API; delete: (path: string) => API; docOutputForamt?: (out: unknown) => unknown; docs?: IAPIDoc; formatOutputReverse?: (out: unknown) => [null | Error, unknown]; get: (path: string) => API; patch: (path: string) => API; post: (path: string) => API; put: (path: string) => API; [key: string]: unknown; } ``` -------------------------------- ### Initialize Theme and Show Page Source: https://github.com/yourtion/node-erest/blob/main/docs/modules.html This snippet initializes the theme based on local storage or OS preference and then displays the page content. It uses a timeout to ensure the application is ready before showing the page, or removes a display:none style if the app is not available. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Set Theme and Show Page - JavaScript Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/IApiOptionInfo.html This snippet demonstrates setting the theme from local storage and conditionally displaying the page content after a short delay. It handles the initial display state and ensures the application is ready before showing the page. ```javascript IApiOptionInfo | erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os";document.body.style.display="none";setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Get Response Checker Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Returns a response checker function that validates API responses against a given schema. ```TypeScript responseChecker(): (data: unknown, schema: ISchemaType) => Record | { message: string; ok: boolean; value: unknown } ``` -------------------------------- ### Get Parameter Checker Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Provides an instance of a parameter checker. This checker validates input parameters against a defined schema. ```TypeScript paramsChecker(): (name: string, value: unknown, schema: ISchemaType) => unknown ``` -------------------------------- ### Theme and Display Initialization Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/IGruop.html This snippet demonstrates client-side JavaScript for initializing the theme based on local storage and controlling the initial display of the body element until the application is ready. ```JavaScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Theme Setting and Initial Display Logic Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/IApiInfo.html This JavaScript snippet handles the initial theme setting based on localStorage and controls the initial display of the application. It hides the body and then reveals it or shows the app page after a short delay. ```JavaScript localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Get Schema Checker Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Retrieves a schema checker instance for validating data structures against a schema definition. It can also handle 'requiredOneOf' conditions. ```TypeScript schemaChecker(): (data: unknown, schema: Record, requiredOneOf?: string[]) => Record ``` -------------------------------- ### Get API Params Check Instance Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Returns an instance for checking API parameters. This function facilitates the validation of incoming request data against a defined schema. ```TypeScript apiParamsCheck(): (data: unknown, schema: Record) => Record ``` -------------------------------- ### Theme and Display Initialization Source: https://github.com/yourtion/node-erest/blob/main/docs/functions/schemaChecker.html Initializes the theme based on local storage or OS preference and sets up a timeout to display the page content, ensuring the app is ready or falling back to a default display. ```JavaScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Get Type Manager Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Retrieves the type manager, which handles the registration and retrieval of custom types. It also includes functionality to validate and format input values based on registered types. ```TypeScript get type(): { get: ( name: string, ) => | undefined | ZodType>; has: (name: string) => boolean; register: (name: string, schema: ZodType) => default; value: ( type: string, input: unknown, params?: unknown, format?: boolean, ) => { message: string; ok: boolean; value: unknown }; } ``` -------------------------------- ### Initialize Theme and Show App Source: https://github.com/yourtion/node-erest/blob/main/docs/variables/zodTypeMap.html This snippet initializes the application's theme based on local storage or OS preference and controls the initial display of the body, showing the app page after a short delay. ```javascript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize Theme and Show Page Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/ISchemaType.html This snippet initializes the theme based on localStorage or OS preference and controls the display of the page content. It hides the body initially and then shows the page content after a short delay, or if the app object is available. ```JavaScript ISchemaType | erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize Theme and Show Page Source: https://github.com/yourtion/node-erest/blob/main/docs/types/genSchema.html This code snippet initializes the theme based on local storage or OS preference, hides the body initially, and then shows the page content after a short delay, potentially calling an app.showPage() method. ```JavaScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Theme and Display Logic Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/APICommon.html This snippet demonstrates client-side JavaScript logic for setting the theme based on local storage and controlling the initial display of the body element. It ensures the application is shown after a short delay or when the app object is available. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Theme and Display Initialization Source: https://github.com/yourtion/node-erest/blob/main/docs/functions/paramsChecker.html This snippet demonstrates how to set the theme based on local storage and initially hide the body content, with a timeout to reveal it or show a specific page. ```JavaScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### API Integration Pattern Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Demonstrates the API integration pattern for testing. It covers initializing the ERest service, creating API endpoints, and asserting that APIs are registered correctly. ```typescript describe("API Integration", () => { let apiService, api; beforeEach(() => { apiService = createTestERestInstance(); api = apiService.api; }); test("should register API correctly", () => { const userApi = createGetApi(api, "/users", "Get Users"); assertApiRegistered(api, "get", "/users", "GET_/users"); }); }); ``` -------------------------------- ### SUPPORT_METHOD Constant (TypeScript) Source: https://github.com/yourtion/node-erest/blob/main/docs/variables/SUPPORT_METHOD.html Defines the SUPPORT_METHOD constant as a readonly array of strings, representing common HTTP methods (GET, POST, PUT, DELETE, PATCH). This constant is used for API request methods. ```typescript SUPPORT_METHOD: readonly ["get", "post", "put", "delete", "patch"] = ... ``` -------------------------------- ### Set Theme and Display Page (JavaScript) Source: https://github.com/yourtion/node-erest/blob/main/docs/types/SUPPORT_METHODS.html This snippet demonstrates how to set the theme based on local storage or OS preference, hide the body initially, and then display the page content after a short delay, potentially showing a specific app page. ```JavaScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize Test System Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Initializes the testing system with an application instance and optional paths for test and documentation files. It's used to set up supertest for testing. ```TypeScript initTest(app: unknown, testPath?: string, docPath?: string): void ``` -------------------------------- ### TypeScript: Router Testing Source: https://github.com/yourtion/node-erest/blob/main/src/test/QUICK_REFERENCE.md Shows how to test router bindings and verify API registration within an Express application. Includes binding a router and asserting the registration of a specific API endpoint. ```typescript // Test router binding const router = express.Router(); apiService.bindRouter(router, apiService.checkerExpress); // Verify API registration assertApiRegistered(api, "get", "/users", "GET_/users"); ``` -------------------------------- ### Type-Safe API Request Body with Zod Source: https://github.com/yourtion/node-erest/blob/main/docs/index.html This example shows how to define a complex data model using Zod for request body validation in ERest. It ensures type safety for incoming data, making API development more robust. ```TypeScript import { z } from 'erest'; // 定义复杂的数据模型 const CreateUserSchema = z.object({ name: z.string().min(1).max(50), email: z.string().email(), age: z.number().int().min(18).max(120), tags: z.array(z.string()).optional(), profile: z.object({ bio: z.string().optional(), avatar: z.string().url().optional(), }).optional(), }); api.api.post('/users') .group('user') .title('创建用户') .body(CreateUserSchema) .register(async (req, res) => { // req.body 自动获得完整的类型推导 const userData = req.body; // 类型安全! const user = await createUser(userData); res.json({ success: true, data: user }); }); ``` -------------------------------- ### Initialize Theme and Display Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html This snippet sets the document's theme based on local storage and initially hides the body content, revealing it after a short delay or when the application is ready. It's a common pattern for managing UI state and initial loading. ```JavaScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Set Theme and Display Page (JavaScript) Source: https://github.com/yourtion/node-erest/blob/main/docs/variables/SUPPORT_METHOD.html This snippet sets the document's theme based on local storage or OS preference, hides the body, and then reveals the page content after a short delay, potentially showing a specific page if the 'app' object is available. ```javascript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Router Testing Pattern Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Shows how to test router configuration in ERest. It covers binding a router, setting up middleware, and verifying the correct order of middleware execution. ```typescript describe("Router Configuration", () => { test("should bind routes with correct middleware order", () => { const apiService = createTestERestInstance(); const router = express.Router(); const hooks = createStandardHooks(); // Setup API with hooks api.get("/test") .before(hooks.beforHook) .middlewares(hooks.middleware) .register(handler); apiService.bindRouter(router, apiService.checkerExpress); // Verify middleware order const routerStack = router.stack[0].route?.stack; assertRouterStackOrder(routerStack, [ "beforHook", "apiParamsChecker", "middleware", "handler" ]); }); }); ``` -------------------------------- ### Set Theme and Show Page Source: https://github.com/yourtion/node-erest/blob/main/docs/hierarchy.html This snippet sets the theme based on local storage or OS preference and controls the initial display of the page content. It waits for the application to be ready or a timeout to reveal the page. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Generate API Documentation and SDK Source: https://github.com/yourtion/node-erest/blob/main/docs/index.html This code snippet illustrates how ERest can automatically generate API documentation in various formats (Swagger, Markdown, Postman) and also create a client SDK using axios. ```TypeScript // 生成多种格式的文档 api.docs.generateDocs({ swagger: './docs/swagger.json', markdown: './docs/api.md', postman: './docs/postman.json', axios: './sdk/api-client.js', }); ``` -------------------------------- ### Generate API Documentation and SDK with ERest Source: https://github.com/yourtion/node-erest/blob/main/README.md This TypeScript snippet illustrates how to use ERest's `generateDocs` method to produce API documentation in various formats (Swagger, Markdown, Postman) and generate a client SDK using Axios. ```typescript // 生成多种格式的文档 api.docs.generateDocs({ swagger: './docs/swagger.json', markdown: './docs/api.md', postman: './docs/postman.json', axios: './sdk/api-client.js', }); ``` -------------------------------- ### Initialize ERest and Define API Endpoint Source: https://github.com/yourtion/node-erest/blob/main/docs/index.html This snippet demonstrates how to initialize the ERest framework, define an API endpoint for fetching user information with parameter and query validation using Zod, and register it with an Express router. ```TypeScript import ERest, { z } from 'erest'; import express from 'express'; // 创建 ERest 实例 const api = new ERest({ info: { title: 'My API', description: 'A powerful API built with ERest', version: new Date(), host: 'http://localhost:3000', basePath: '/api', }, groups: { user: '用户管理', post: '文章管理', }, }); // 定义 API 接口 api.api.get('/users/:id') .group('user') .title('获取用户信息') .params(z.object({ id: z.string().describe('用户ID'), })) .query(z.object({ include: z.string().optional().describe('包含的关联数据'), })) .register(async (req, res) => { const { id } = req.params; const { include } = req.query; // 业务逻辑 const user = await getUserById(id, include); res.json({ success: true, data: user }); }); // 绑定到 Express const app = express(); const router = express.Router(); app.use('/api', router); api.bindRouter(router, api.checkerExpress); app.listen(3000, () => { console.log('🚀 Server running on http://localhost:3000'); }); ``` -------------------------------- ### Set Theme and Display Page Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/INumericParams.html This snippet demonstrates how to set the theme based on local storage or OS preference, hide the body initially, and then display the page content after a short delay, potentially showing an application page or removing the display style. ```JavaScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Data Management Best Practice Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Highlights best practices for data management in tests, recommending the use of fixtures for complex data, creating reusable parameter definitions, and avoiding hardcoded values. ```typescript // Good const testData = apiFixtures.userTestData; assertSchemaValidation(checker, testData.valid, schema, testData.expected); // Avoid assertSchemaValidation(checker, { name: "John", age: 30 }, schema, { name: "John", age: 30 }); ``` -------------------------------- ### Generate Project Framework with yo erest Source: https://github.com/yourtion/node-erest/blob/main/README.md This section demonstrates how to use the 'generator-erest' Yeoman generator to quickly scaffold new API projects. It provides commands for generating projects based on Express or @leizm/web. ```bash npm install generator-erest -g # Express 项目 yo erest:express # @leizm/web 项目 yo erest:lei-web ``` -------------------------------- ### Set Theme and Show Page - TypeScript Source: https://github.com/yourtion/node-erest/blob/main/docs/types/TYPE_RESPONSE.html This snippet demonstrates how to set the theme based on local storage or OS preference, hide the body initially, and then show the page content after a short delay, potentially calling an app.showPage() method. ```TypeScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### TypeScript: Common Parameters Source: https://github.com/yourtion/node-erest/blob/main/src/test/QUICK_REFERENCE.md Lists and demonstrates the usage of common parameters available through the `commonParams` object, such as ID, name, age, and email. ```typescript import { commonParams } from "./utils/api-helpers"; // Available parameters commonParams.id // String ID parameter commonParams.name // String name parameter commonParams.age // Number age parameter commonParams.email // String email parameter ``` -------------------------------- ### Theme and Display Initialization Source: https://github.com/yourtion/node-erest/blob/main/docs/functions/isISchemaType.html Initializes the document's theme from local storage and controls the initial display of the body element, showing the app or removing the display style after a short delay. ```JavaScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Type Helpers for TypeScript Testing Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Provides type-safe utilities for testing with TypeScript support. Includes common type definitions, type-safe test data, and helpers for Zod schemas. ```typescript // Common type definitions const commonTypes = { stringRequired: TypeDefinition, numberOptional: TypeDefinition, // ... more types }; // Type-safe test data const typeTestData = { validString: "test", validNumber: 42, // ... more test data }; // Zod schema helpers const zodSchemas = { userSchema: z.object({ name: z.string(), age: z.number() }), // ... more schemas }; ``` -------------------------------- ### Test Organization Best Practice Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Illustrates best practices for organizing tests, emphasizing grouping related tests with descriptive `describe` blocks, consistent naming, and separating concerns. ```typescript describe("Component - Feature Category", () => { describe("Specific Functionality", () => { test("should handle specific scenario", () => { // Test implementation }); }); }); ``` -------------------------------- ### Parameter Validation Pattern Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Demonstrates the parameter validation pattern in tests. It shows how to build parameter definitions and assert validation for both required and invalid inputs using helper functions. ```typescript describe("Parameter Validation", () => { test("should validate required parameters", () => { const param = build(TYPES.String, "Name", true); // Test valid input assertParamValidation(checker, "name", "John", param, "John"); // Test invalid input assertParamValidationError(checker, "name", null, param, /required/); }); }); ``` -------------------------------- ### TypeScript - Theme and Display Logic Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/IEnumParams.html This snippet demonstrates how to retrieve a theme preference from localStorage, set a default if none is found, and then conditionally display the application or remove a display:none style after a delay. It's likely part of the client-side initialization logic. ```typescript IEnumParams | erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Mock Factories for Test Data Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Provides factory functions for generating consistent mock data and functions, including mock hooks, standard hook sets, mock request/response objects, and test data sets for users and APIs. ```TypeScript const mockHook = createMockHook("hookName"); const hooks = createStandardHooks(); // Returns: { globalBefore, globalAfter, beforHook, middleware } const mockReq = createMockRequest({ body: { name: "John" } }); const mockRes = createMockResponse(); const userData = createUserTestData(); const apiData = createApiTestData(); ``` ```TypeScript import { createMockHook, createStandardHooks } from "./utils/mock-factories"; test("should handle hooks correctly", () => { const hooks = createStandardHooks(); api .get("/test") .before(hooks.beforHook) .middlewares(hooks.middleware) .register(handler); // Test hook execution order }); ``` -------------------------------- ### Assertion Helpers for Testing Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Offers specialized assertion functions for common testing scenarios, including parameter validation, schema validation, API registration checks, router stack order, and generic error handling. ```TypeScript assertParamValidation(checker, paramName, inputValue, paramDef, expectedOutput); assertParamValidationError(checker, paramName, inputValue, paramDef, errorPattern); assertSchemaValidation(checker, inputData, schema, expectedOutput, requiredOneOf?); assertSchemaValidationError(checker, inputData, schema, errorPattern, requiredOneOf?); assertApiRegistered(api, method, path, expectedKey); assertRouterStackOrder(routerStack, expectedOrder); assertThrowsWithMessage(fn, messagePattern); ``` ```TypeScript import { assertParamValidation, assertSchemaValidation } from "./utils/assertion-helpers"; test("should validate parameters correctly", () => { const stringParam = build(TYPES.String, "Name", true); // Test successful validation assertParamValidation(paramsChecker, "name", "John", stringParam, "John"); // Test validation error assertParamValidationError( paramsChecker, "name", null, stringParam, /missing required parameter/ ); }); ``` -------------------------------- ### Generate Documentation Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Generates documentation for the API. It allows specifying a save path for the documentation and an option to wait for program exit before saving. ```TypeScript genDocs(savePath?: string, onExit?: boolean): void ``` -------------------------------- ### Error Testing with Assertions Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Demonstrates how to test both successful and failed parameter validation scenarios using assertion helpers. It highlights the use of specific error patterns to validate error messages effectively. ```typescript assertParamValidation(checker, "email", "test@example.com", emailParam, "test@example.com"); assertParamValidationError(checker, "email", "invalid-email", emailParam, /should be valid Email/); ``` -------------------------------- ### Configure Mock Data Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/APIOption.html Allows for the configuration of mock data for API requests. This is useful for testing purposes. ```TypeScript mock?: Record ``` -------------------------------- ### Set Theme and Display Document Source: https://github.com/yourtion/node-erest/blob/main/docs/types/SchemaType.html This snippet demonstrates how to retrieve the theme preference from localStorage, set it on the document's dataset, hide the body, and then reveal it after a short delay, potentially showing an application page. ```JavaScript erestdocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Default Class Constructor Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html The constructor for the Default class initializes the API helper with provided options. It is generic and accepts a type parameter T, defaulting to DEFAULT_HANDLER. ```TypeScript new default(options: IApiOption): default ``` -------------------------------- ### Schema Validation Pattern Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Illustrates the schema validation pattern for testing. It includes tests for validating a complete schema with valid data and handling validation errors with invalid data. ```typescript describe("Schema Validation", () => { test("should validate complete schema", () => { const schema = schemaFixtures.userSchema; const validData = schemaFixtures.testData.validUser; assertSchemaValidation(checker, validData, schema, validData); }); test("should handle validation errors", () => { const schema = schemaFixtures.userSchema; const invalidData = schemaFixtures.testData.invalidUser; assertSchemaValidationError(checker, invalidData, schema, /missing.*email/); }); }); ``` -------------------------------- ### Define IDocOptions Interface for Documentation Generation Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/IDocOptions.html This TypeScript interface defines the options available for generating API documentation. Each property, when set to a string or boolean, enables the generation of a specific documentation format. ```TypeScript interface IDocOptions { [all]?: string | boolean; [axios]?: string | boolean; [home]?: string | boolean; [index]?: string | boolean; [json]?: string | boolean; [markdown]?: string | boolean; [postman]?: string | boolean; [swagger]?: string | boolean; [wiki]?: string | boolean; [key: string]: unknown; } ``` -------------------------------- ### Set Document Output Format (TypeScript) Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Sets a function to format the output for documentation. This function takes an unknown input and returns an unknown output. It is defined in the library's source code. ```TypeScript setDocOutputForamt(fn: (out: unknown) => unknown): void ``` -------------------------------- ### IApiOptionInfo Interface Definition - TypeScript Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/IApiOptionInfo.html Defines the IApiOptionInfo interface, which represents basic information for an API. It includes optional properties for basePath, description, host, title, and version. ```typescript interface IApiOptionInfo { [basePath](#basepath)?: string; [description](#description)?: string; [host](#host)?: string; [title](#title)?: string; [version](#version)?: Date; } ``` -------------------------------- ### Register Doc Plugin Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Registers a documentation generation plugin with a given name. This allows for extending the documentation generation capabilities of the framework. ```TypeScript addDocPlugin(name: string, plugin: IDocGeneratePlugin): void ``` -------------------------------- ### Migration: Old vs. New Parameter Validation Pattern Source: https://github.com/yourtion/node-erest/blob/main/src/test/README.md Compares the 'before' and 'after' patterns for parameter validation tests. The 'after' pattern utilizes assertion helpers for clearer intent and better error reporting. ```typescript test("parameter validation", () => { const param = build(TYPES.String, "Name", true); expect(paramsChecker("name", "John", param)).toBe("John"); expect(() => paramsChecker("name", null, param)).toThrow(); }); ``` ```typescript test("should validate string parameters", () => { const param = build(TYPES.String, "Name", true); assertParamValidation(paramsChecker, "name", "John", param, "John"); assertParamValidationError(paramsChecker, "name", null, param, /missing required parameter/); }); ``` -------------------------------- ### Build Swagger Information Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Retrieves Swagger information for the API. This function does not take any parameters and returns an array of unknown types, presumably representing the Swagger specification. ```TypeScript buildSwagger(): unknown[] ``` -------------------------------- ### Define IApiOption Interface Source: https://github.com/yourtion/node-erest/blob/main/docs/interfaces/IApiOption.html This TypeScript code defines the IApiOption interface, which specifies optional configurations for an API. It includes properties for documentation options, force grouping, group definitions, API information, and custom error handlers for internal, invalid parameter, and missing parameter errors, as well as an optional path. ```TypeScript interface IApiOption { [docs](#docs)?: [IDocOptions](IDocOptions.html); [forceGroup](#forcegroup)?: boolean; [groups](#groups)?: Record; [info](#info)?: [IApiOptionInfo](IApiOptionInfo.html); [internalError](#internalerror)?: (msg: string) => Error; [invalidParameterError](#invalidparametererror)?: (msg: string) => Error; [missingParameterError](#missingparametererror)?: (msg: string) => Error; [path](#path)?: string; } ``` -------------------------------- ### Create Schema with Zod Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Creates a schema object using Zod for data validation. It takes a schema object as input and returns a ZodObject. ```TypeScript createSchema(schemaObj: Record): ZodObject<{[key: string]: ZodType>}> ``` -------------------------------- ### Set Format Output (TypeScript) Source: https://github.com/yourtion/node-erest/blob/main/docs/classes/default.html Sets a function to format test outputs. This function receives an unknown input and returns a tuple containing either null or an Error, along with an unknown output. It is defined in the library's source code. ```TypeScript setFormatOutput(fn: (out: unknown) => [null | Error, unknown]): void ```