lambder 1.0.131 → 1.0.133

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
@@ -5,11 +5,9 @@ Lambder is a highly opinionated dynamic serverless framework designed to facilit
5
5
  ## Features
6
6
 
7
7
  - **Simple API & Route Declaration**: Define your APIs and routes using concise and expressive syntax.
8
- - **Type-Safe API Contracts**: Full TypeScript type safety across frontend and backend with zero runtime overhead.
9
8
  - **Session Management**: Built-in session management to secure and personalize user experiences.
10
9
  - **Flexible Hooks System**: Employ hooks to execute code at different stages of the request lifecycle, enabling fine-grained control over the application flow.
11
10
  - **Error Handling**: Comprehensive error handling capabilities, including global error handlers and route-specific fallbacks.
12
- - **MSW Mocking Support**: Optional Mock Service Worker integration for easy API mocking in tests and development.
13
11
  - **Seamless Integration**: Designed to work effortlessly with AWS Lambda and API Gateway, providing a straightforward path to deploy serverless applications.
14
12
 
15
13
  ## Installation
@@ -546,52 +544,41 @@ const user = await caller.api('getUserById', { userId: '123' });
546
544
 
547
545
  📖 **[Read the Quick Start Guide](docs/TYPE_SAFE_QUICK_START.md)** for more details and examples!
548
546
 
549
- ## Testing & Mocking with MSW
547
+ ## Testing with LambderMSW
550
548
 
551
- Lambder provides optional integration with [Mock Service Worker (MSW)](https://mswjs.io/) for easy API mocking in tests and development.
552
-
553
- ### Installation
554
-
555
- ```bash
556
- npm install --save-dev msw
557
- ```
558
-
559
- ### Quick Example
549
+ LambderMSW provides seamless integration with [MSW (Mock Service Worker)](https://mswjs.io/) for testing your APIs. It works perfectly with type-safe API contracts!
560
550
 
561
551
  ```typescript
562
- import { mockLambderApi } from 'lambder';
552
+ import { LambderMSW } from 'lambder';
563
553
  import { setupServer } from 'msw/node';
564
- import type { MyApiContract } from './apiContract';
554
+ import type { MyApiContract } from './shared/apiContract';
555
+
556
+ const lambderMSW = new LambderMSW<MyApiContract>({
557
+ apiPath: '/api',
558
+ });
565
559
 
566
- // Create type-safe mock handlers
567
560
  const handlers = [
568
- mockLambderApi<MyApiContract, 'getUserById'>(
569
- 'getUserById',
570
- (input) => ({
571
- id: input.userId,
572
- name: 'Test User',
573
- email: 'test@example.com'
574
- })
575
- )
561
+ // Mock API with full type safety! ✨
562
+ lambderMSW.mockApi('getUserById', async (payload) => {
563
+ return {
564
+ id: payload.userId,
565
+ name: 'John Doe',
566
+ email: 'john@example.com'
567
+ };
568
+ }),
569
+
570
+ // Mock errors, delays, and more
571
+ lambderMSW.mockApi('createUser', async (payload) => {
572
+ return { id: '123', ...payload };
573
+ }, { delay: 500 }),
574
+
575
+ lambderMSW.mockSessionExpired('protectedApi'),
576
576
  ];
577
577
 
578
- // Set up MSW server
579
578
  const server = setupServer(...handlers);
580
-
581
- beforeAll(() => server.listen());
582
- afterEach(() => server.resetHandlers());
583
- afterAll(() => server.close());
584
579
  ```
585
580
 
586
- ### Benefits
587
-
588
- ✅ **Type-Safe Mocking** - Full TypeScript support for mock responses
589
- ✅ **Easy Setup** - Simple functions that match your API contract
590
- ✅ **Test Scenarios** - Mock errors, session expired, not authorized, etc.
591
- ✅ **Development Mode** - Use mocks while developing frontend features
592
- ✅ **Storybook Ready** - Perfect for component stories
593
-
594
- 📖 **[Read the MSW Mocking Guide](docs/MSW_MOCKING.md)** for detailed setup and examples!
581
+ 📖 **[Read the LambderMSW Guide](docs/LAMBDER_MSW.md)** for complete testing documentation!
595
582
 
596
583
  ## Contributing
597
584
 
@@ -1,102 +1,49 @@
1
- import type { ApiContractShape } from './LambderApiContract.js';
2
- /**
3
- * Creates a mock handler for a Lambder API endpoint
4
- *
5
- * @example
6
- * ```typescript
7
- * mockLambderApi('public.getInitialPageData', () => ({
8
- * userLocationData: { ... },
9
- * sessionUser: null
10
- * }))
11
- * ```
12
- *
13
- * @example with dynamic response based on input
14
- * ```typescript
15
- * mockLambderApi('user.updateProfile', (input) => ({
16
- * success: true,
17
- * userId: input.userId
18
- * }))
19
- * ```
20
- */
21
- export declare function mockLambderApi<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, responseFactory: (input: TContract[TApiName]['input']) => TContract[TApiName]['output'] | Promise<TContract[TApiName]['output']>, options?: {
22
- /** Custom API path, defaults to '/api' */
23
- apiPath?: string;
24
- /** Delay in ms before responding (for testing loading states) */
1
+ import type { ApiContractShape } from './LambderApiContract';
2
+ type RequestHandler = any;
3
+ type MockApiOptions = {
4
+ versionExpired?: boolean;
5
+ sessionExpired?: boolean;
6
+ notAuthorized?: boolean;
7
+ message?: any;
8
+ errorMessage?: any;
9
+ logList?: any[];
25
10
  delay?: number;
26
- /** Custom apiVersion to include in response */
27
- apiVersion?: string | null;
28
- }): any;
29
- /**
30
- * Creates a mock handler that returns an error for a Lambder API endpoint
31
- *
32
- * @example
33
- * ```typescript
34
- * mockLambderApiError('user.deleteAccount', 'Account deletion failed')
35
- * ```
36
- */
37
- export declare function mockLambderApiError<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, errorMessage: string, options?: {
38
- /** Custom API path, defaults to '/api' */
39
- apiPath?: string;
40
- /** Delay in ms before responding */
41
- delay?: number;
42
- /** Custom apiVersion to include in response */
43
- apiVersion?: string | null;
44
- }): any;
45
- /**
46
- * Creates a mock handler that simulates a session expired error
47
- *
48
- * @example
49
- * ```typescript
50
- * mockLambderSessionExpired('user.updateProfile')
51
- * ```
52
- */
53
- export declare function mockLambderSessionExpired<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, options?: {
54
- /** Custom API path, defaults to '/api' */
55
- apiPath?: string;
56
- /** Custom apiVersion to include in response */
57
- apiVersion?: string | null;
58
- }): any;
59
- /**
60
- * Creates a mock handler that simulates a "not authorized" error
61
- *
62
- * @example
63
- * ```typescript
64
- * mockLambderNotAuthorized('admin.deleteUser')
65
- * ```
66
- */
67
- export declare function mockLambderNotAuthorized<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, options?: {
68
- /** Custom API path, defaults to '/api' */
69
- apiPath?: string;
70
- /** Custom apiVersion to include in response */
71
- apiVersion?: string | null;
72
- }): any;
73
- /**
74
- * Creates a mock handler that simulates a version expired error
75
- *
76
- * @example
77
- * ```typescript
78
- * mockLambderVersionExpired('user.updateProfile')
79
- * ```
80
- */
81
- export declare function mockLambderVersionExpired<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, options?: {
82
- /** Custom API path, defaults to '/api' */
83
- apiPath?: string;
84
- /** Custom apiVersion to include in response */
85
- apiVersion?: string | null;
86
- }): any;
87
- /**
88
- * Helper to combine multiple Lambder mock handlers
89
- * Since each handler checks for its specific apiName, you can just spread them into setupWorker/setupServer
90
- *
91
- * @deprecated This helper is not needed - just spread handlers directly into setupWorker/setupServer
92
- * @example
93
- * ```typescript
94
- * import { setupServer } from 'msw/node';
95
- *
96
- * const server = setupServer(
97
- * mockLambderApi('user.getProfile', () => ({ name: 'Test User' })),
98
- * mockLambderApi('user.updateProfile', (input) => ({ success: true }))
99
- * );
100
- * ```
101
- */
102
- export declare function createLambderApiHandler(apiPath: string, handlers: any[]): any[];
11
+ };
12
+ export default class LambderMSW<TContract extends ApiContractShape = any> {
13
+ private apiPath;
14
+ private apiVersion?;
15
+ private http;
16
+ private HttpResponse;
17
+ constructor({ apiPath, apiVersion, }: {
18
+ apiPath: string;
19
+ apiVersion?: string;
20
+ });
21
+ /**
22
+ * Mock an API endpoint with MSW
23
+ * @param apiName - The name of the API to mock
24
+ * @param handler - Function that returns the mock payload
25
+ * @param options - Additional response options (session expired, version expired, etc.)
26
+ */
27
+ mockApi<TApiName extends keyof TContract & string>(apiName: TApiName, handler: (payload?: TContract[TApiName]['input']) => Promise<TContract[TApiName]['output']> | TContract[TApiName]['output'], options?: MockApiOptions): RequestHandler;
28
+ /**
29
+ * Mock an API endpoint that returns a session expired error
30
+ */
31
+ mockSessionExpired<TApiName extends keyof TContract & string>(apiName: TApiName): RequestHandler;
32
+ /**
33
+ * Mock an API endpoint that returns a version expired error
34
+ */
35
+ mockVersionExpired<TApiName extends keyof TContract & string>(apiName: TApiName): RequestHandler;
36
+ /**
37
+ * Mock an API endpoint that returns a not authorized error
38
+ */
39
+ mockNotAuthorized<TApiName extends keyof TContract & string>(apiName: TApiName): RequestHandler;
40
+ /**
41
+ * Mock an API endpoint that returns an error message
42
+ */
43
+ mockError<TApiName extends keyof TContract & string>(apiName: TApiName, errorMessage: string): RequestHandler;
44
+ /**
45
+ * Mock an API endpoint with a custom message
46
+ */
47
+ mockWithMessage<TApiName extends keyof TContract & string>(apiName: TApiName, handler: (payload?: TContract[TApiName]['input']) => Promise<TContract[TApiName]['output']> | TContract[TApiName]['output'], message: any): RequestHandler;
48
+ }
49
+ export {};
@@ -1,176 +1,109 @@
1
- /**
2
- * Creates a mock handler for a Lambder API endpoint
3
- *
4
- * @example
5
- * ```typescript
6
- * mockLambderApi('public.getInitialPageData', () => ({
7
- * userLocationData: { ... },
8
- * sessionUser: null
9
- * }))
10
- * ```
11
- *
12
- * @example with dynamic response based on input
13
- * ```typescript
14
- * mockLambderApi('user.updateProfile', (input) => ({
15
- * success: true,
16
- * userId: input.userId
17
- * }))
18
- * ```
19
- */
20
- export function mockLambderApi(apiName, responseFactory, options) {
21
- const apiPath = options?.apiPath ?? '/api';
22
- const delay = options?.delay ?? 0;
23
- const apiVersion = options?.apiVersion ?? null;
24
- // @ts-ignore - MSW is an optional peer dependency
25
- const { http, HttpResponse } = require('msw');
26
- return http.post(apiPath, async ({ request }) => {
27
- const body = (await request.json());
28
- // Only handle this specific API
29
- if (body.apiName !== apiName) {
30
- return;
1
+ export default class LambderMSW {
2
+ apiPath;
3
+ apiVersion;
4
+ http;
5
+ HttpResponse;
6
+ constructor({ apiPath, apiVersion, }) {
7
+ this.apiPath = apiPath;
8
+ this.apiVersion = apiVersion;
9
+ // Dynamically import MSW - it needs to be installed by the user
10
+ try {
11
+ const msw = require('msw');
12
+ this.http = msw.http;
13
+ this.HttpResponse = msw.HttpResponse;
31
14
  }
32
- console.log(`[MSW Lambder] Mocking ${apiName}`, body.payload);
33
- // Apply delay if specified
34
- if (delay > 0) {
35
- await new Promise((resolve) => setTimeout(resolve, delay));
15
+ catch (err) {
16
+ throw new Error('MSW (Mock Service Worker) is required. Install it with: npm install msw --save-dev');
36
17
  }
37
- // Generate the response
38
- const payload = await responseFactory(body.payload);
39
- // Return in Lambder API response format
40
- return HttpResponse.json({
41
- ...(apiVersion !== null ? { apiVersion } : {}),
42
- payload,
18
+ }
19
+ /**
20
+ * Mock an API endpoint with MSW
21
+ * @param apiName - The name of the API to mock
22
+ * @param handler - Function that returns the mock payload
23
+ * @param options - Additional response options (session expired, version expired, etc.)
24
+ */
25
+ mockApi(apiName, handler, options) {
26
+ return this.http.post(this.apiPath, async ({ request }) => {
27
+ let body;
28
+ try {
29
+ body = await request.json();
30
+ }
31
+ catch (parseErr) {
32
+ // If JSON parsing fails, return undefined to let other handlers try
33
+ console.warn("LambderMSW: Failed to parse request body as JSON");
34
+ return;
35
+ }
36
+ // Check if body is valid and has apiName
37
+ if (!body || typeof body.apiName !== 'string') {
38
+ // Invalid request format, let other handlers try
39
+ return;
40
+ }
41
+ console.log("LambderMSW called for:", body.apiName, "matching against:", apiName);
42
+ // Check if this is the API we're mocking
43
+ if (body.apiName !== apiName) {
44
+ // If this handler doesn't match, return undefined to let MSW try other handlers
45
+ return;
46
+ }
47
+ try {
48
+ // Add artificial delay if specified
49
+ if (options?.delay) {
50
+ await new Promise(resolve => setTimeout(resolve, options.delay));
51
+ }
52
+ // Call the handler with the payload from the request
53
+ const payload = await handler(body.payload);
54
+ console.log("Matched! Returning payload for:", apiName);
55
+ const response = {
56
+ apiVersion: this.apiVersion,
57
+ payload,
58
+ ...(options?.versionExpired ? { versionExpired: options.versionExpired } : {}),
59
+ ...(options?.sessionExpired ? { sessionExpired: options.sessionExpired } : {}),
60
+ ...(options?.notAuthorized ? { notAuthorized: options.notAuthorized } : {}),
61
+ ...(options?.message ? { message: options.message } : {}),
62
+ ...(options?.errorMessage ? { errorMessage: options.errorMessage } : {}),
63
+ ...(options?.logList?.length ? { logList: options.logList } : {}),
64
+ };
65
+ return this.HttpResponse.json(response);
66
+ }
67
+ catch (err) {
68
+ // Only handle errors that occur during handler execution for matched APIs
69
+ console.error("Error in LambderMSW handler for", apiName, ":", err);
70
+ const errorResponse = {
71
+ apiVersion: this.apiVersion,
72
+ payload: null,
73
+ errorMessage: err.message || "Unknown error",
74
+ };
75
+ return this.HttpResponse.json(errorResponse, { status: 500 });
76
+ }
43
77
  });
44
- });
45
- }
46
- /**
47
- * Creates a mock handler that returns an error for a Lambder API endpoint
48
- *
49
- * @example
50
- * ```typescript
51
- * mockLambderApiError('user.deleteAccount', 'Account deletion failed')
52
- * ```
53
- */
54
- export function mockLambderApiError(apiName, errorMessage, options) {
55
- const apiPath = options?.apiPath ?? '/api';
56
- const delay = options?.delay ?? 0;
57
- const apiVersion = options?.apiVersion ?? null;
58
- // @ts-ignore - MSW is an optional peer dependency
59
- const { http, HttpResponse } = require('msw');
60
- return http.post(apiPath, async ({ request }) => {
61
- const body = (await request.json());
62
- if (body.apiName !== apiName) {
63
- return;
64
- }
65
- console.log(`[MSW Lambder] Mocking error for ${apiName}:`, errorMessage);
66
- if (delay > 0) {
67
- await new Promise((resolve) => setTimeout(resolve, delay));
68
- }
69
- return HttpResponse.json({
70
- ...(apiVersion !== null ? { apiVersion } : {}),
71
- payload: null,
72
- errorMessage,
73
- });
74
- });
75
- }
76
- /**
77
- * Creates a mock handler that simulates a session expired error
78
- *
79
- * @example
80
- * ```typescript
81
- * mockLambderSessionExpired('user.updateProfile')
82
- * ```
83
- */
84
- export function mockLambderSessionExpired(apiName, options) {
85
- const apiPath = options?.apiPath ?? '/api';
86
- const apiVersion = options?.apiVersion ?? null;
87
- // @ts-ignore - MSW is an optional peer dependency
88
- const { http, HttpResponse } = require('msw');
89
- return http.post(apiPath, async ({ request }) => {
90
- const body = (await request.json());
91
- if (body.apiName !== apiName) {
92
- return;
93
- }
94
- console.log(`[MSW Lambder] Mocking session expired for ${apiName}`);
95
- return HttpResponse.json({
96
- ...(apiVersion !== null ? { apiVersion } : {}),
97
- payload: null,
98
- sessionExpired: true,
99
- errorMessage: 'Session expired',
100
- });
101
- });
102
- }
103
- /**
104
- * Creates a mock handler that simulates a "not authorized" error
105
- *
106
- * @example
107
- * ```typescript
108
- * mockLambderNotAuthorized('admin.deleteUser')
109
- * ```
110
- */
111
- export function mockLambderNotAuthorized(apiName, options) {
112
- const apiPath = options?.apiPath ?? '/api';
113
- const apiVersion = options?.apiVersion ?? null;
114
- // @ts-ignore - MSW is an optional peer dependency
115
- const { http, HttpResponse } = require('msw');
116
- return http.post(apiPath, async ({ request }) => {
117
- const body = (await request.json());
118
- if (body.apiName !== apiName) {
119
- return;
120
- }
121
- console.log(`[MSW Lambder] Mocking not authorized for ${apiName}`);
122
- return HttpResponse.json({
123
- ...(apiVersion !== null ? { apiVersion } : {}),
124
- payload: null,
125
- notAuthorized: true,
126
- errorMessage: 'Not authorized',
127
- });
128
- });
129
- }
130
- /**
131
- * Creates a mock handler that simulates a version expired error
132
- *
133
- * @example
134
- * ```typescript
135
- * mockLambderVersionExpired('user.updateProfile')
136
- * ```
137
- */
138
- export function mockLambderVersionExpired(apiName, options) {
139
- const apiPath = options?.apiPath ?? '/api';
140
- const apiVersion = options?.apiVersion ?? null;
141
- // @ts-ignore - MSW is an optional peer dependency
142
- const { http, HttpResponse } = require('msw');
143
- return http.post(apiPath, async ({ request }) => {
144
- const body = (await request.json());
145
- if (body.apiName !== apiName) {
146
- return;
147
- }
148
- console.log(`[MSW Lambder] Mocking version expired for ${apiName}`);
149
- return HttpResponse.json({
150
- ...(apiVersion !== null ? { apiVersion } : {}),
151
- payload: null,
152
- versionExpired: true,
153
- errorMessage: 'Version expired',
154
- });
155
- });
156
- }
157
- /**
158
- * Helper to combine multiple Lambder mock handlers
159
- * Since each handler checks for its specific apiName, you can just spread them into setupWorker/setupServer
160
- *
161
- * @deprecated This helper is not needed - just spread handlers directly into setupWorker/setupServer
162
- * @example
163
- * ```typescript
164
- * import { setupServer } from 'msw/node';
165
- *
166
- * const server = setupServer(
167
- * mockLambderApi('user.getProfile', () => ({ name: 'Test User' })),
168
- * mockLambderApi('user.updateProfile', (input) => ({ success: true }))
169
- * );
170
- * ```
171
- */
172
- export function createLambderApiHandler(apiPath, handlers) {
173
- // This is deprecated - users should just spread handlers directly
174
- // Kept for backward compatibility
175
- return handlers;
78
+ }
79
+ /**
80
+ * Mock an API endpoint that returns a session expired error
81
+ */
82
+ mockSessionExpired(apiName) {
83
+ return this.mockApi(apiName, async () => null, { sessionExpired: true });
84
+ }
85
+ /**
86
+ * Mock an API endpoint that returns a version expired error
87
+ */
88
+ mockVersionExpired(apiName) {
89
+ return this.mockApi(apiName, async () => null, { versionExpired: true });
90
+ }
91
+ /**
92
+ * Mock an API endpoint that returns a not authorized error
93
+ */
94
+ mockNotAuthorized(apiName) {
95
+ return this.mockApi(apiName, async () => null, { notAuthorized: true });
96
+ }
97
+ /**
98
+ * Mock an API endpoint that returns an error message
99
+ */
100
+ mockError(apiName, errorMessage) {
101
+ return this.mockApi(apiName, async () => null, { errorMessage });
102
+ }
103
+ /**
104
+ * Mock an API endpoint with a custom message
105
+ */
106
+ mockWithMessage(apiName, handler, message) {
107
+ return this.mockApi(apiName, handler, { message });
108
+ }
176
109
  }
package/dist/index.d.ts CHANGED
@@ -4,5 +4,5 @@ export { default as LambderCaller } from "./LambderCaller.js";
4
4
  export { default as LambderResponseBuilder } from "./LambderResponseBuilder.js";
5
5
  export { default as LambderResolver } from "./LambderResolver.js";
6
6
  export { default as LambderSessionManager } from "./LambderSessionManager.js";
7
+ export { default as LambderMSW } from "./LambderMSW.js";
7
8
  export { type ApiContractShape, type ApiContract, type ApiInput, type ApiOutput, } from "./LambderApiContract.js";
8
- export { mockLambderApi, mockLambderApiError, mockLambderSessionExpired, mockLambderNotAuthorized, mockLambderVersionExpired, createLambderApiHandler, } from "./LambderMSW.js";
package/dist/index.js CHANGED
@@ -4,5 +4,4 @@ export { default as LambderCaller } from "./LambderCaller.js";
4
4
  export { default as LambderResponseBuilder } from "./LambderResponseBuilder.js";
5
5
  export { default as LambderResolver } from "./LambderResolver.js";
6
6
  export { default as LambderSessionManager } from "./LambderSessionManager.js";
7
- // MSW mocking utilities (optional - requires msw to be installed)
8
- export { mockLambderApi, mockLambderApiError, mockLambderSessionExpired, mockLambderNotAuthorized, mockLambderVersionExpired, createLambderApiHandler, } from "./LambderMSW.js";
7
+ export { default as LambderMSW } from "./LambderMSW.js";