jax-hono 1.0.20 → 1.0.21

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/helpers/config.ts CHANGED
@@ -1,23 +1,23 @@
1
- import type { JaxConfig } from '../types/config';
2
-
3
- type PlainConfig = Record<string, unknown>;
4
-
5
- export type PluginConfigItem =
6
- | false
7
- | {
8
- enable?: boolean;
9
- package?: string;
10
- options?: unknown;
11
- };
12
-
13
- export type PluginConfig = Record<string, PluginConfigItem>;
14
-
15
- export function defineConfig<TProjectConfig extends PlainConfig = PlainConfig>(
16
- config: Partial<JaxConfig & TProjectConfig>
17
- ) {
18
- return config;
19
- }
20
-
21
- export function definePluginConfig<TPluginConfig extends PluginConfig>(config: TPluginConfig) {
22
- return config;
23
- }
1
+ import type { JaxConfig } from '../types/config';
2
+
3
+ type PlainConfig = Record<string, unknown>;
4
+
5
+ export type PluginConfigItem =
6
+ | false
7
+ | {
8
+ enable?: boolean;
9
+ package?: string;
10
+ options?: unknown;
11
+ };
12
+
13
+ export type PluginConfig = Record<string, PluginConfigItem>;
14
+
15
+ export function defineConfig<TProjectConfig extends PlainConfig = PlainConfig>(
16
+ config: Partial<JaxConfig & TProjectConfig>
17
+ ) {
18
+ return config;
19
+ }
20
+
21
+ export function definePluginConfig<TPluginConfig extends PluginConfig>(config: TPluginConfig) {
22
+ return config;
23
+ }
package/helpers/crud.ts CHANGED
@@ -1,27 +1,27 @@
1
- import { normalizeRoutePath } from './route';
2
- import type { Handler, Hono } from 'hono';
3
-
4
- export type JaxCrudController = {
5
- index: Handler;
6
- show: Handler;
7
- create: Handler;
8
- update: Handler;
9
- destroy: Handler;
10
- };
11
-
12
- export function registerCrudRoutes<TApp extends Hono>(
13
- app: TApp,
14
- path: string,
15
- controller: JaxCrudController
16
- ): TApp {
17
- const basePath = normalizeRoutePath(path);
18
- const detailPath = basePath === '/' ? '/:id' : `${basePath}/:id`;
19
-
20
- app.get(basePath, controller.index);
21
- app.get(detailPath, controller.show);
22
- app.post(basePath, controller.create);
23
- app.put(detailPath, controller.update);
24
- app.delete(detailPath, controller.destroy);
25
-
26
- return app;
27
- }
1
+ import { normalizeRoutePath } from './route';
2
+ import type { Handler, Hono } from 'hono';
3
+
4
+ export type JaxCrudController = {
5
+ index: Handler;
6
+ show: Handler;
7
+ create: Handler;
8
+ update: Handler;
9
+ destroy: Handler;
10
+ };
11
+
12
+ export function registerCrudRoutes<TApp extends Hono>(
13
+ app: TApp,
14
+ path: string,
15
+ controller: JaxCrudController
16
+ ): TApp {
17
+ const basePath = normalizeRoutePath(path);
18
+ const detailPath = basePath === '/' ? '/:id' : `${basePath}/:id`;
19
+
20
+ app.get(basePath, controller.index);
21
+ app.get(detailPath, controller.show);
22
+ app.post(basePath, controller.create);
23
+ app.put(detailPath, controller.update);
24
+ app.delete(detailPath, controller.destroy);
25
+
26
+ return app;
27
+ }
package/helpers/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- export * from "./route";
2
- export * from "./config";
3
- export * from "./crud";
4
- export * from "../plugins/define";
1
+ export * from "./route";
2
+ export * from "./config";
3
+ export * from "./crud";
4
+ export * from "../plugins/define";
package/helpers/route.ts CHANGED
@@ -1,7 +1,7 @@
1
- export function normalizeRoutePath(path: string) {
2
- if (!path || path === '/') {
3
- return '/';
4
- }
5
-
6
- return `/${path.replace(/^\/+|\/+$/g, '')}`;
7
- }
1
+ export function normalizeRoutePath(path: string) {
2
+ if (!path || path === '/') {
3
+ return '/';
4
+ }
5
+
6
+ return `/${path.replace(/^\/+|\/+$/g, '')}`;
7
+ }
package/index.ts CHANGED
@@ -1,121 +1,121 @@
1
- import { Hono } from 'hono';
2
- import './core/hono';
3
- import './middleware/api-response';
4
- import { createHono, createApi } from './core/hono';
5
- import { registerCrudRoutes } from './helpers/crud';
6
- import type { Config } from './config';
7
- import type * as AppModule from './core/app';
8
- import {
9
- requireGeneratedModule,
10
- type GeneratedControllers,
11
- type GeneratedModels,
12
- type GeneratedServices,
13
- } from './core/generated';
14
-
15
- type AppRuntimeModule = typeof AppModule;
16
- type Controllers = GeneratedControllers;
17
- type Models = GeneratedModels;
18
- type CreateServices = (deps: unknown) => GeneratedServices;
19
-
20
- let appRuntimeModule: AppRuntimeModule | undefined;
21
- let controllersModule: { controllers: Controllers } | undefined;
22
- let modelsModule: { models: Models } | undefined;
23
- let servicesModule: { createServices: CreateServices } | undefined;
24
- let configModule: { default: Config } | undefined;
25
-
26
- function getAppRuntimeModule() {
27
- appRuntimeModule ??= require('./core/app') as AppRuntimeModule;
28
-
29
- return appRuntimeModule;
30
- }
31
-
32
- function getControllers() {
33
- controllersModule ??= requireGeneratedModule('controllers.generated.ts') as {
34
- controllers: Controllers;
35
- };
36
-
37
- return controllersModule.controllers;
38
- }
39
-
40
- function getModels() {
41
- modelsModule ??= requireGeneratedModule('models.generated.ts') as { models: Models };
42
-
43
- return modelsModule.models;
44
- }
45
-
46
- function getCreateServices() {
47
- servicesModule ??= requireGeneratedModule('services.generated.ts') as {
48
- createServices: CreateServices;
49
- };
50
-
51
- return servicesModule.createServices;
52
- }
53
-
54
- function getConfig() {
55
- configModule ??= require('./config') as { default: Config };
56
-
57
- return configModule.default;
58
- }
59
-
60
- export { createHono, createApi, registerCrudRoutes };
61
- export { defineConfig, definePluginConfig } from './helpers/config';
62
- export { definePlugin } from './plugins/define';
63
- export type { AppContext, AppPlugin } from './core/app';
64
- export type { Config, JaxConfig } from './config';
65
- export { ApiController } from './core/api-controller';
66
- export { Controller } from './core/controller';
67
- export { Service } from './core/service';
68
- export type { ServiceContext } from './core/service';
69
- export { defineCron } from './core/cron';
70
- export type { CronJob, CronRunContext, CronSchedule } from './core/cron';
71
- export type Services = GeneratedServices;
72
- export type { ApiFailResponse, ApiResponse, ApiSuccessResponse } from './middleware/api-response';
73
-
74
- export function createApp() {
75
- return getAppRuntimeModule().createApp({
76
- models: getModels(),
77
- createServices: getCreateServices()
78
- });
79
- }
80
-
81
- export const controllers = new Proxy({} as Controllers, {
82
- get(_target, property, receiver) {
83
- return Reflect.get(getControllers(), property, receiver);
84
- },
85
- has(_target, property) {
86
- return property in getControllers();
87
- },
88
- ownKeys() {
89
- return Reflect.ownKeys(getControllers());
90
- },
91
- getOwnPropertyDescriptor(_target, property) {
92
- return Object.getOwnPropertyDescriptor(getControllers(), property);
93
- }
94
- });
95
-
96
- export const models = new Proxy({} as Models, {
97
- get(_target, property, receiver) {
98
- return Reflect.get(getModels(), property, receiver);
99
- }
100
- });
101
-
102
- export const createServices: CreateServices = ((deps: unknown) => {
103
- return getCreateServices()(deps);
104
- }) as CreateServices;
105
-
106
- export const config = new Proxy({} as Config, {
107
- get(_target, property, receiver) {
108
- return Reflect.get(getConfig(), property, receiver);
109
- },
110
- has(_target, property) {
111
- return property in getConfig();
112
- },
113
- ownKeys() {
114
- return Reflect.ownKeys(getConfig());
115
- },
116
- getOwnPropertyDescriptor(_target, property) {
117
- return Object.getOwnPropertyDescriptor(getConfig(), property);
118
- }
119
- });
120
-
121
- export { Hono };
1
+ import { Hono } from 'hono';
2
+ import './core/hono';
3
+ import './middleware/api-response';
4
+ import { createHono, createApi } from './core/hono';
5
+ import { registerCrudRoutes } from './helpers/crud';
6
+ import type { Config } from './config';
7
+ import type * as AppModule from './core/app';
8
+ import {
9
+ requireGeneratedModule,
10
+ type GeneratedControllers,
11
+ type GeneratedModels,
12
+ type GeneratedServices,
13
+ } from './core/generated';
14
+
15
+ type AppRuntimeModule = typeof AppModule;
16
+ type Controllers = GeneratedControllers;
17
+ type Models = GeneratedModels;
18
+ type CreateServices = (deps: unknown) => GeneratedServices;
19
+
20
+ let appRuntimeModule: AppRuntimeModule | undefined;
21
+ let controllersModule: { controllers: Controllers } | undefined;
22
+ let modelsModule: { models: Models } | undefined;
23
+ let servicesModule: { createServices: CreateServices } | undefined;
24
+ let configModule: { default: Config } | undefined;
25
+
26
+ function getAppRuntimeModule() {
27
+ appRuntimeModule ??= require('./core/app') as AppRuntimeModule;
28
+
29
+ return appRuntimeModule;
30
+ }
31
+
32
+ function getControllers() {
33
+ controllersModule ??= requireGeneratedModule('controllers.generated.ts') as {
34
+ controllers: Controllers;
35
+ };
36
+
37
+ return controllersModule.controllers;
38
+ }
39
+
40
+ function getModels() {
41
+ modelsModule ??= requireGeneratedModule('models.generated.ts') as { models: Models };
42
+
43
+ return modelsModule.models;
44
+ }
45
+
46
+ function getCreateServices() {
47
+ servicesModule ??= requireGeneratedModule('services.generated.ts') as {
48
+ createServices: CreateServices;
49
+ };
50
+
51
+ return servicesModule.createServices;
52
+ }
53
+
54
+ function getConfig() {
55
+ configModule ??= require('./config') as { default: Config };
56
+
57
+ return configModule.default;
58
+ }
59
+
60
+ export { createHono, createApi, registerCrudRoutes };
61
+ export { defineConfig, definePluginConfig } from './helpers/config';
62
+ export { definePlugin } from './plugins/define';
63
+ export type { AppContext, AppPlugin } from './core/app';
64
+ export type { Config, JaxConfig } from './config';
65
+ export { ApiController } from './core/api-controller';
66
+ export { Controller } from './core/controller';
67
+ export { Service } from './core/service';
68
+ export type { ServiceContext } from './core/service';
69
+ export { defineCron } from './core/cron';
70
+ export type { CronJob, CronRunContext, CronSchedule } from './core/cron';
71
+ export type Services = GeneratedServices;
72
+ export type { ApiFailResponse, ApiResponse, ApiSuccessResponse } from './middleware/api-response';
73
+
74
+ export function createApp() {
75
+ return getAppRuntimeModule().createApp({
76
+ models: getModels(),
77
+ createServices: getCreateServices()
78
+ });
79
+ }
80
+
81
+ export const controllers = new Proxy({} as Controllers, {
82
+ get(_target, property, receiver) {
83
+ return Reflect.get(getControllers(), property, receiver);
84
+ },
85
+ has(_target, property) {
86
+ return property in getControllers();
87
+ },
88
+ ownKeys() {
89
+ return Reflect.ownKeys(getControllers());
90
+ },
91
+ getOwnPropertyDescriptor(_target, property) {
92
+ return Object.getOwnPropertyDescriptor(getControllers(), property);
93
+ }
94
+ });
95
+
96
+ export const models = new Proxy({} as Models, {
97
+ get(_target, property, receiver) {
98
+ return Reflect.get(getModels(), property, receiver);
99
+ }
100
+ });
101
+
102
+ export const createServices: CreateServices = ((deps: unknown) => {
103
+ return getCreateServices()(deps);
104
+ }) as CreateServices;
105
+
106
+ export const config = new Proxy({} as Config, {
107
+ get(_target, property, receiver) {
108
+ return Reflect.get(getConfig(), property, receiver);
109
+ },
110
+ has(_target, property) {
111
+ return property in getConfig();
112
+ },
113
+ ownKeys() {
114
+ return Reflect.ownKeys(getConfig());
115
+ },
116
+ getOwnPropertyDescriptor(_target, property) {
117
+ return Object.getOwnPropertyDescriptor(getConfig(), property);
118
+ }
119
+ });
120
+
121
+ export { Hono };
@@ -1,44 +1,44 @@
1
- import type { Context, MiddlewareHandler } from 'hono';
2
-
3
- export type ApiSuccessResponse<T = unknown> = {
4
- code: 0;
5
- msg: string;
6
- data?: T;
7
- };
8
-
9
- export type ApiFailResponse = {
10
- code: 1;
11
- msg: string;
12
- };
13
-
14
- export type ApiResponse<T = unknown> = ApiSuccessResponse<T> | ApiFailResponse;
15
-
16
- export function ok<T>(c: Context, data?: T, msg = 'success'): Response {
17
- return c.json<ApiSuccessResponse<T>>({
18
- code: 0,
19
- msg,
20
- data
21
- });
22
- }
23
-
24
- export function fail(c: Context, msg: string): Response {
25
- return c.json<ApiFailResponse>({
26
- code: 1,
27
- msg
28
- });
29
- }
30
-
31
- declare module 'hono' {
32
- interface Context {
33
- ok: <T>(data?: T, msg?: string) => Response;
34
- fail: (msg: string) => Response;
35
- }
36
- }
37
-
38
- export const apiResponse: MiddlewareHandler = async (c, next) => {
39
- // 把统一响应方法挂到 Hono Context 上,业务接口直接使用 c.ok / c.fail。
40
- c.ok = <T>(data?: T, msg = 'success') => ok(c, data, msg);
41
- c.fail = (msg: string) => fail(c, msg);
42
-
43
- await next();
44
- };
1
+ import type { Context, MiddlewareHandler } from 'hono';
2
+
3
+ export type ApiSuccessResponse<T = unknown> = {
4
+ code: 0;
5
+ msg: string;
6
+ data?: T;
7
+ };
8
+
9
+ export type ApiFailResponse = {
10
+ code: 1;
11
+ msg: string;
12
+ };
13
+
14
+ export type ApiResponse<T = unknown> = ApiSuccessResponse<T> | ApiFailResponse;
15
+
16
+ export function ok<T>(c: Context, data?: T, msg = 'success'): Response {
17
+ return c.json<ApiSuccessResponse<T>>({
18
+ code: 0,
19
+ msg,
20
+ data
21
+ });
22
+ }
23
+
24
+ export function fail(c: Context, msg: string): Response {
25
+ return c.json<ApiFailResponse>({
26
+ code: 1,
27
+ msg
28
+ });
29
+ }
30
+
31
+ declare module 'hono' {
32
+ interface Context {
33
+ ok: <T>(data?: T, msg?: string) => Response;
34
+ fail: (msg: string) => Response;
35
+ }
36
+ }
37
+
38
+ export const apiResponse: MiddlewareHandler = async (c, next) => {
39
+ // 把统一响应方法挂到 Hono Context 上,业务接口直接使用 c.ok / c.fail。
40
+ c.ok = <T>(data?: T, msg = 'success') => ok(c, data, msg);
41
+ c.fail = (msg: string) => fail(c, msg);
42
+
43
+ await next();
44
+ };
package/middleware/jwt.ts CHANGED
@@ -1,90 +1,90 @@
1
- import config from "../config";
2
- import jwt from "jsonwebtoken";
3
- import type { Context, MiddlewareHandler, Next } from "hono";
4
-
5
- type JwtAuthOptions<
6
- TPayload extends Record<string, any> = Record<string, any>,
7
- > = {
8
- secretSuffix: string;
9
- stateKey: string;
10
- validate?: (payload: TPayload, c: Context) => boolean | Promise<boolean>;
11
- resolveState?: (payload: TPayload, c: Context) => unknown | Promise<unknown>;
12
- };
13
-
14
- function createJwtAuth<
15
- TPayload extends Record<string, any> = Record<string, any>,
16
- >(options: JwtAuthOptions<TPayload>): MiddlewareHandler {
17
- return async (c, next) => {
18
- const session = c.var.session;
19
- const sessionData = await session.get();
20
-
21
- if (sessionData && sessionData[options.stateKey]) {
22
- c.state[options.stateKey] = sessionData[options.stateKey];
23
- await next();
24
- return;
25
- }
26
-
27
- // const session = c.get('session');
28
- // const sessionData = session.get(options.stateKey);
29
-
30
- // if (sessionData) {
31
- // c.state[options.stateKey] = sessionData;
32
- // await next();
33
- // }
34
-
35
- const token = getAuthorizationToken(c);
36
-
37
- if (!token) {
38
- return c.json({ code: 401, msg: "请先登录" });
39
- }
40
-
41
- try {
42
- const payload = jwt.verify(
43
- token,
44
- (config as any).jwt.secret + options.secretSuffix,
45
- ) as TPayload;
46
- const valid = options.validate
47
- ? await options.validate(payload, c)
48
- : true;
49
-
50
- if (!valid) {
51
- return c.json({ code: 401, msg: "请重新登录" });
52
- }
53
-
54
- const stateValue = options.resolveState
55
- ? await options.resolveState(payload, c)
56
- : payload;
57
-
58
- if (!stateValue) {
59
- return c.json({ code: 401, msg: "请重新登录" });
60
- }
61
-
62
- c.state[options.stateKey] = stateValue;
63
-
64
- await next();
65
- } catch {
66
- return c.json({ code: 401, msg: "请重新登录" });
67
- }
68
- };
69
- }
70
-
71
- function createOptionalAuth(auth: MiddlewareHandler): MiddlewareHandler {
72
- return async (c, next) => {
73
- if (!c.req.header("authorization")) {
74
- await next();
75
- return;
76
- }
77
-
78
- return auth(c, next as Next);
79
- };
80
- }
81
-
82
- function getAuthorizationToken(c: Context) {
83
- const authorization = c.req.header("authorization") ?? "";
84
-
85
- return authorization.startsWith("Bearer ")
86
- ? authorization.slice("Bearer ".length)
87
- : authorization;
88
- }
89
-
90
- export { createJwtAuth, createOptionalAuth, getAuthorizationToken };
1
+ import config from "../config";
2
+ import jwt from "jsonwebtoken";
3
+ import type { Context, MiddlewareHandler, Next } from "hono";
4
+
5
+ type JwtAuthOptions<
6
+ TPayload extends Record<string, any> = Record<string, any>,
7
+ > = {
8
+ secretSuffix: string;
9
+ stateKey: string;
10
+ validate?: (payload: TPayload, c: Context) => boolean | Promise<boolean>;
11
+ resolveState?: (payload: TPayload, c: Context) => unknown | Promise<unknown>;
12
+ };
13
+
14
+ function createJwtAuth<
15
+ TPayload extends Record<string, any> = Record<string, any>,
16
+ >(options: JwtAuthOptions<TPayload>): MiddlewareHandler {
17
+ return async (c, next) => {
18
+ const session = c.var.session;
19
+ const sessionData = await session.get();
20
+
21
+ if (sessionData && sessionData[options.stateKey]) {
22
+ c.state[options.stateKey] = sessionData[options.stateKey];
23
+ await next();
24
+ return;
25
+ }
26
+
27
+ // const session = c.get('session');
28
+ // const sessionData = session.get(options.stateKey);
29
+
30
+ // if (sessionData) {
31
+ // c.state[options.stateKey] = sessionData;
32
+ // await next();
33
+ // }
34
+
35
+ const token = getAuthorizationToken(c);
36
+
37
+ if (!token) {
38
+ return c.json({ code: 401, msg: "请先登录" });
39
+ }
40
+
41
+ try {
42
+ const payload = jwt.verify(
43
+ token,
44
+ (config as any).jwt.secret + options.secretSuffix,
45
+ ) as TPayload;
46
+ const valid = options.validate
47
+ ? await options.validate(payload, c)
48
+ : true;
49
+
50
+ if (!valid) {
51
+ return c.json({ code: 401, msg: "请重新登录" });
52
+ }
53
+
54
+ const stateValue = options.resolveState
55
+ ? await options.resolveState(payload, c)
56
+ : payload;
57
+
58
+ if (!stateValue) {
59
+ return c.json({ code: 401, msg: "请重新登录" });
60
+ }
61
+
62
+ c.state[options.stateKey] = stateValue;
63
+
64
+ await next();
65
+ } catch {
66
+ return c.json({ code: 401, msg: "请重新登录" });
67
+ }
68
+ };
69
+ }
70
+
71
+ function createOptionalAuth(auth: MiddlewareHandler): MiddlewareHandler {
72
+ return async (c, next) => {
73
+ if (!c.req.header("authorization")) {
74
+ await next();
75
+ return;
76
+ }
77
+
78
+ return auth(c, next as Next);
79
+ };
80
+ }
81
+
82
+ function getAuthorizationToken(c: Context) {
83
+ const authorization = c.req.header("authorization") ?? "";
84
+
85
+ return authorization.startsWith("Bearer ")
86
+ ? authorization.slice("Bearer ".length)
87
+ : authorization;
88
+ }
89
+
90
+ export { createJwtAuth, createOptionalAuth, getAuthorizationToken };
@@ -1,3 +1,3 @@
1
- import { logger } from 'hono/logger';
2
-
3
- export const requestLog = logger();
1
+ import { logger } from 'hono/logger';
2
+
3
+ export const requestLog = logger();