-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathstl.ts
More file actions
1238 lines (1146 loc) · 36.1 KB
/
stl.ts
File metadata and controls
1238 lines (1146 loc) · 36.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as z from "./z";
import { openapiSpec } from "./openapiSpec";
import type { oas31 } from "zod-openapi";
type OpenAPIObject = oas31.OpenAPIObject;
import { fromZodError } from "zod-validation-error/v3";
import coerceParams from "./coerceParams";
export { openapiSpec };
export { type SelectTree, parseSelect } from "./parseSelect";
export { z };
export { createClient } from "./client";
export { createRecursiveProxy } from "./createRecursiveProxy";
export {
type StainlessClient,
type CreateClientOptions,
ClientPromise,
type ClientPromiseProps,
PaginatorPromise,
type Page,
type RequestOptions,
} from "./client";
export { getApiRouteMap } from "./gen/getApiRouteMap";
/** The standard HTTP methods, in lowercase. */
export type HttpMethod =
| "GET"
| "POST"
| "PUT"
| "PATCH"
| "DELETE"
| "OPTIONS"
| "HEAD";
/**
* A type for a string representing an HTTP path.
* Must begin with a leading `/`.
*/
export type HttpPath = `/${string}`;
/**
* Defines the HTTP method and path by which an endpoint
* is accessed.
*/
export type HttpEndpoint = `${HttpMethod} ${HttpPath}`;
export type GetEndpointMethod<E extends AnyEndpoint> = GetHttpEndpointMethod<
E["endpoint"]
>;
export type GetHttpEndpointMethod<E extends HttpEndpoint> =
E extends `${infer M extends HttpMethod} ${string}` ? M : never;
export type GetEndpointUrl<E extends AnyEndpoint> = GetHttpEndpointUrl<
E["endpoint"]
>;
export type GetHttpEndpointUrl<E extends HttpEndpoint> =
E extends `${HttpMethod} ${infer Url}` ? Url : never;
export function parseEndpoint<E extends HttpEndpoint>(
endpoint: E
): [GetHttpEndpointMethod<E>, GetHttpEndpointUrl<E>] {
const [method, path] = endpoint.split(/\s+/, 2);
switch (method) {
case "GET":
case "POST":
case "PUT":
case "PATCH":
case "DELETE":
case "OPTIONS":
case "HEAD":
break;
default:
throw new Error(`invalid or unsupported http method: ${method}`);
}
if (!path.startsWith("/")) {
throw new Error(
`Invalid path must start with a slash (/); got: "${endpoint}"`
);
}
return [method as GetHttpEndpointMethod<E>, path as GetHttpEndpointUrl<E>];
}
/**
* Ensures that the input and output types are both
* objects; plays well with z.object(...).transform(() => ({...}))
* whereas z.AnyZodObject doesn't.
*/
export type ZodObjectSchema = z.ZodType<object, any, object>;
/**
* Endpoints take in `handler` methods of this type.
*/
export type Handler<
Ctx,
Path extends ZodObjectSchema | undefined,
Query extends ZodObjectSchema | undefined,
Body extends ZodObjectSchema | undefined,
Response
> = (
/** request object with parsed params */
request: RequestData<Path, Query, Body>,
/** context with stainless, plugin, and user-provided data */
ctx: Ctx
) => Response | Promise<Response>;
/**
* An object merging properties from path, query, and body params
*/
export type RequestData<
Path extends ZodObjectSchema | undefined,
Query extends ZodObjectSchema | undefined,
Body extends ZodObjectSchema | undefined
> = (Path extends z.ZodTypeAny ? z.infer<Path> : {}) &
(Query extends z.ZodTypeAny ? z.infer<Query> : {}) &
(Body extends z.ZodTypeAny ? z.infer<Body> : {});
/**
* An interface for per-endpoint configuration, accessible to and extendable by
* plugins/middleware.
*
* When creating endpoints, users can specify a `config` object of
* type `EndpointConfig`. This allows plugins to accept custom properties.
*
* ```ts
* // example-plugin.ts
* declare module "stainless" {
* // This interface must be declared within the "stainless" module
* interface EndpointConfig {
* rateLimit?: number,
* }
* }
*
* // api/users/retrieve.ts
*
* stl.endpoint(
* endpoint: "GET /api/users/{userId}",
* response: User,
* config: {
* rateLimit: 10,
* },
* ...
* }
* )
* ```
*/
export interface EndpointConfig {
// auth etc goes here.
}
const coercedPath = Symbol("coercedPath");
const coercedQuery = Symbol("coercedQuery");
export interface BaseEndpoint<
Config extends EndpointConfig | undefined,
MethodAndUrl extends HttpEndpoint,
Path extends ZodObjectSchema | undefined,
Query extends ZodObjectSchema | undefined,
Body extends ZodObjectSchema | undefined,
Response extends z.ZodTypeAny | undefined
> {
stl: Stl<any>;
summary?: string;
description?: string;
endpoint: MethodAndUrl;
response: Response;
config: Config;
path: Path;
[coercedPath]?: Path;
query: Query;
[coercedQuery]?: Query;
body: Body;
}
export type AnyBaseEndpoint = BaseEndpoint<any, any, any, any, any, any>;
/**
* An endpoint created on an instance of {@link Stl} via the
* {@link Stl.endpoint} method.
*/
export interface Endpoint<
Config extends EndpointConfig | undefined,
MethodAndUrl extends HttpEndpoint,
Path extends ZodObjectSchema | undefined,
Query extends ZodObjectSchema | undefined,
Body extends ZodObjectSchema | undefined,
Response extends z.ZodTypeAny | undefined
> extends BaseEndpoint<Config, MethodAndUrl, Path, Query, Body, Response> {
handler?: Handler<
StlContext<BaseEndpoint<Config, MethodAndUrl, Path, Query, Body, Response>>,
Path,
Query,
Body,
Response extends z.ZodTypeAny ? z.input<Response> : undefined
>;
}
export type AnyEndpoint = Endpoint<any, any, any, any, any, any>;
export type EndpointPathInput<E extends AnyEndpoint> =
E["path"] extends z.ZodTypeAny ? z.input<E["path"]> : undefined;
export type EndpointPathOutput<E extends AnyEndpoint> =
E["path"] extends z.ZodTypeAny ? z.output<E["path"]> : undefined;
export type EndpointQueryInput<E extends AnyEndpoint> =
E["query"] extends z.ZodTypeAny ? z.input<E["query"]> : undefined;
export type EndpointQueryOutput<E extends AnyEndpoint> =
E["query"] extends z.ZodTypeAny ? z.output<E["query"]> : undefined;
export type EndpointHasRequiredQuery<E extends AnyEndpoint> =
E["query"] extends z.ZodTypeAny
? {} extends EndpointQueryInput<E>
? false
: true
: false;
export type EndpointBodyInput<E extends AnyEndpoint> =
E["body"] extends z.ZodTypeAny ? z.input<E["body"]> : undefined;
export type EndpointBodyOutput<E extends AnyEndpoint> =
E["body"] extends z.ZodTypeAny ? z.output<E["body"]> : undefined;
export type EndpointResponseInput<E extends AnyEndpoint> =
E["response"] extends z.ZodTypeAny ? z.input<E["response"]> : undefined;
export type EndpointResponseOutput<E extends AnyEndpoint> =
E["response"] extends z.ZodTypeAny ? z.output<E["response"]> : undefined;
/**
* Gets all endpoints associated with a given resource
*/
export function allEndpoints(
resource:
| AnyResourceConfig
| Pick<AnyResourceConfig, "actions" | "namespacedResources">
): AnyEndpoint[] {
return [
...Object.keys(resource.actions || {})
.map((k) => resource.actions[k])
.filter(Boolean),
...Object.keys(resource.namespacedResources || {}).flatMap((k) =>
allEndpoints(resource.namespacedResources[k])
),
];
}
export type AnyActionsConfig = Record<string, AnyEndpoint | null>;
/**
* A resource configuration created by {@link Stl.resource}.
*/
export type ResourceConfig<
Actions extends AnyActionsConfig | undefined,
NamespacedResources extends
| Record<string, ResourceConfig<any, any, any>>
| undefined,
Models extends Record<string, z.ZodTypeAny> | undefined
> = {
summary: string;
internal?: boolean;
actions: Actions;
namespacedResources: NamespacedResources;
models: Models;
};
export type AnyResourceConfig = ResourceConfig<any, any, any>;
type OpenAPIConfig = {
endpoint: HttpEndpoint | false;
spec: OpenAPIObject;
};
export const apiSymbol = Symbol("api");
export function isAPIDescription(value: unknown): value is AnyAPIDescription {
return (value as any)?.[apiSymbol] === true;
}
/**
* A type containing information about an API defined by the
* {@link Stl.api} method.
*/
export type APIDescription<
BasePath extends HttpPath,
TopLevel extends ResourceConfig<AnyActionsConfig, undefined, any> | undefined,
Resources extends Record<string, AnyResourceConfig> | undefined
> = {
[apiSymbol]: true;
basePath: BasePath;
openapi: OpenAPIConfig;
topLevel: TopLevel;
resources: Resources;
};
export type APIRouteMap = {
actions?: Record<string, RouteMapAction>;
namespacedResources?: Record<string, APIRouteMap>;
};
export type RouteMapAction = {
endpoint: HttpEndpoint;
};
export type AnyAPIDescription = APIDescription<any, any, any>;
export const isStlError = (value: unknown): value is StlError => {
return value instanceof StlError || (value as any)?._isStlError === true;
};
/**
* Throw `StlError` and its subclasses within endpoint `handler` methods
* to return 4xx or 5xx HTTP error responses to the user, with well-formatted
* bodies.
*
* `StlError` is best used to create custom subclasses if you need HTTP status
* codes we don't yet provide out of the box.
*/
export class StlError extends Error {
_isStlError = true;
/**
* @param statusCode
* @param response optional data included in the body of the response JSON.
*/
constructor(
public statusCode: number,
public response?: Record<string, any>
) {
super(JSON.stringify(response));
}
}
/** When thrown in an endpoint handler, responds with HTTP status code 400. */
export class BadRequestError extends StlError {
/**
* @param response optional data included in the body of the response JSON.
*/
constructor(response?: Record<string, any>) {
super(400, { error: "bad request", ...response });
Object.setPrototypeOf(this, StlError.prototype);
}
}
/** When thrown in an endpoint handler, responds with HTTP status code 401. */
export class UnauthorizedError extends StlError {
/**
* @param response optional data included in the body of the response JSON.
*/
constructor(response?: Record<string, any>) {
super(401, { error: "unauthorized", ...response });
Object.setPrototypeOf(this, StlError.prototype);
}
}
/** When thrown in an endpoint handler, responds with HTTP status code 403. */
export class ForbiddenError extends StlError {
/**
* @param response optional data included in the body of the response JSON.
*/
constructor(response?: Record<string, any>) {
super(403, { error: "forbidden", ...response });
Object.setPrototypeOf(this, StlError.prototype);
}
}
/** When thrown in an endpoint handler, responds with HTTP status code 404. */
export class NotFoundError extends StlError {
/**
* @param response optional data included in the body of the response JSON.
*/
constructor(response?: Record<string, any>) {
super(404, { error: "not found", ...response });
Object.setPrototypeOf(this, StlError.prototype);
}
}
type AnyStatics = Record<string, any>; // TODO?
export type StainlessPlugin<
Statics extends AnyStatics | undefined = undefined
> = {
/**
* Optionally provide data to every endpoint handler.
* This will be available under {@link StlContext.plugins},
* under the field with the user's name for the plugin.
*/
statics?: Statics;
/**
* Optionally inject middleware on each endpoint handler
* to customize their behavior.
* @param params parsed parameters of the request
* @param context request context, potentially including
* endpoint-specific configuration
*/
middleware?: <EC extends AnyEndpoint>(
params: Params,
context: StlContext<EC>
) => void | Promise<void>;
};
/**
* An interface allowing `stainless` to initialize plugins
* passed to the {@link Stl} constructor's `plugins` parameter.
*/
export type MakeStainlessPlugin<
Statics extends AnyStatics | undefined = undefined,
Plugins extends AnyPlugins = {}
> = (stl: Stl<Plugins>) => StainlessPlugin<Statics>;
type AnyPlugins = Record<string, MakeStainlessPlugin<any, any>>;
/**
* Options for customizing the behavior of an {@link Stl} instance.
*/
export type CreateStlOptions<Plugins extends AnyPlugins> = {
/**
* Provide plugins to customize `stainless` endpoint behavior.
* Each plugin is named by the user, and must be of type {@link MakeStainlessPlugin}.
* Some plugins provide context information under `ctx.plugins.{name of plugin}.
*/
plugins: Plugins;
/**
* Injects generated schemas into the `stl` instance.
* `typeSchemas` is exported from the module where you're configured
* codegen schemas to generate in. By default, this is `stl-api-gen`.
*/
typeSchemas?: TypeSchemas;
};
/** The raw headers provided on a request. */
export type StainlessHeaders = Record<string, string | string[] | undefined>; // TODO
/**
* An interface for extending base stainless context information
* with additional data.
*
* In order to extend stainless context, declare an instance of
* `StlCustomContext` within the `stainless` module:
* ```ts
* declare module "stainless" {
* interface StlCustomContext {
* // custom context data here
* }
* }
* ```
*/
export interface StlCustomContext {}
export interface BaseStlContext<EC extends AnyBaseEndpoint> {
/** The current endpoint being processed. */
endpoint: EC; // what is the config?
// url: URL;
/** The raw headers passed to the current request. */
headers: StainlessHeaders;
/** The parsed path, query, and body parameters of the current request. */
parsedParams?: {
path: any;
query: any;
body: any;
};
/**
* Raw server request data and information.
* This will depend on the underlying server implementation
* being used to serve the request, like Next.js or Express. */
server: {
type: string; // eg nextjs
args: unknown[]; // eg [req, rsp]
};
}
/**
* Request data provided to an endpoint. This includes things like
* request parameters and data injected by plugin middleware.
*/
export interface StlContext<EC extends AnyBaseEndpoint>
extends BaseStlContext<EC>,
StlCustomContext {}
/** Parsed, but untyped, parameters provided to an endpoint. */
export interface Params {
path: any;
query: any;
body: any;
headers: any;
}
type ExtractStatics<Plugins extends AnyPlugins> = {
[Name in PluginsWithStaticsKeys<Plugins>]: NonNullable<
ReturnType<Plugins[Name]>["statics"]
>;
};
/**
* Provides static data created by plugins to
* endpoint request handlers.
*/
export type PluginsWithStaticsKeys<Plugins extends AnyPlugins> = {
[k in keyof Plugins]: NonNullable<
ReturnType<Plugins[k]>["statics"]
> extends never
? never
: k;
}[keyof Plugins];
type ExtractExecuteResponse<EC extends AnyEndpoint> =
EC["response"] extends z.ZodTypeAny ? z.infer<EC["response"]> : undefined;
export const OpenAPIResponse = z.object({}).passthrough();
export type OpenAPIResponse = z.infer<typeof OpenAPIResponse>;
/** Type of an endpoint serving OpenAPI schema data. */
export type OpenAPIEndpoint = Endpoint<
any,
any,
undefined,
undefined,
undefined,
typeof OpenAPIResponse
>;
const prependZodPath = (path: string) => (error: any) => {
if (error instanceof z.ZodError) {
for (const issue of error.issues) {
issue.path.unshift(path);
}
}
throw error;
};
/** Extension of top-level API to include serving OpenAPI schema data. */
type OpenAPITopLevel<
openapi extends
| {
endpoint?: HttpEndpoint | false;
}
| undefined
> = openapi extends {
endpoint: false;
}
? {}
: { actions: { getOpenapi: OpenAPIEndpoint } };
/** Parameters for {@link Stl.endpoint}. */
interface CreateEndpointOptions<
MethodAndUrl extends HttpEndpoint,
Config extends EndpointConfig | undefined,
Path extends ZodObjectSchema | undefined,
Query extends ZodObjectSchema | undefined,
Body extends ZodObjectSchema | undefined,
Response extends z.ZodTypeAny = z.ZodVoid
> {
/**
* a string declaring the HTTP method
* and URL for this endpoint, e.g. `"GET /items/{id}"`
*/
endpoint: MethodAndUrl;
/** Optional summary for the endpoint. */
summary?: string;
/** Optional description for the endpoint. */
description?: string;
/** Optional plugin configuration specific to the endpoint. */
config?: Config;
/** The schema for the response defining its properties. */
response?: Response;
/** The schema for the path parameters. */
path?: Path;
/** The schema for the query (search) parameters. */
query?: Query;
/** The schema for the body parameters. */
body?: Body;
/**
* The function that handles requests to the `endpoint`.
* Called with an object holding a combination of the endpoint's
* path, query, and body params, and an {@link StlContext} holding
* additional global and plugin- and endpoint-specific context.
*/
handler?: Handler<
StlContext<BaseEndpoint<Config, MethodAndUrl, Path, Query, Body, Response>>,
Path,
Query,
Body,
Response extends z.ZodTypeAny ? z.input<Response> : undefined
>;
}
/** Parameters for {@link Stl.resource} */
interface CreateResourceOptions<
Actions extends AnyActionsConfig | undefined,
Resources extends Record<string, ResourceConfig<any, any, any>> | undefined,
Models extends Record<string, z.ZodTypeAny> | undefined
> {
/**
* A summary describing the resource;
* included in the generated OpenAPI schema.
*/
summary: string;
/** TODO what does this do, we don't use it for anything... */
internal?: boolean;
/** An object of endpoints for performing methods on the resource. */
actions?: Actions;
/** An object of sub-resources of the resource. */
namespacedResources?: Resources;
/** An object of named models; values must be response schemas. */
models?: Models;
}
/** Parameters for {@link Stl.api} */
interface CreateApiOptions<
BasePath extends HttpPath,
TopLevel extends
| ResourceConfig<AnyActionsConfig, undefined, any>
| undefined = undefined,
Resources extends Record<string, AnyResourceConfig> | undefined = undefined
> {
basePath: BasePath;
/**
* Optionally configure an endpoint for retrieving the API's
* generated OpenAPI schema.
*/
openapi?: {
/**
* The endpoint for serving the OpenAPI schema,
* or `false` to disable schema serving.
*/
endpoint?: HttpEndpoint | false;
};
/**
* Add endpoints directly onto the API, without utilizing the
* resource abstraction. This should be used sparingly,
* as resourceless endpoints are less idiomatic and may result in
* less organized SDKs if misused.
*/
topLevel?: TopLevel;
/** An object containing the resources of which the API is composed. */
resources?: Resources;
}
/**
* The entry-point into using Stainless. Used to create the core
* structures of the framework: endpoints, resources, and APIs.
*
* ## Usage
* Creating an instance is easy:
* ```ts
* export const stl = new Stl({})
* ```
*
* For a higher-level overview of how to use `Stl` to build APIs,
* see [the docs](https://stainlessapi.com/stl/getting-started).
*/
export class Stl<Plugins extends AnyPlugins> {
// this gets filled in later, we just declare the type here.
plugins = {} as ExtractStatics<Plugins>;
private stainlessPlugins: Record<string, StainlessPlugin<any>> = {};
private typeSchemas?: TypeSchemas;
/**
*
* @param opts {CreateStlOptions<Plugins>} customize the created instance with plugins
*/
constructor(opts: CreateStlOptions<Plugins>) {
for (const key in opts.plugins) {
const makePlugin = opts.plugins[key];
const plugin = (this.stainlessPlugins[key] = makePlugin(this));
if (plugin.statics) {
// PluginStatics only allows keys with non-nullable values
// We ensure this is the case by checking that plugin.statics is
// not falsy
// @ts-expect-error
this.plugins[key] = plugin.statics;
}
}
this.typeSchemas = opts.typeSchemas;
}
/**
* Initializes a {@link StlContext} for a request. This should only
* be used for advanced use-cases like implementing a plugin for
* integrating with an underlying server implementation.
* For a usage example, see `../../next/src/nextPlugin.rs`.
* @param c the context to initialize
* @returns initialized context
*/
initContext<EC extends AnyEndpoint>(c: StlContext<EC>): StlContext<EC> {
return c;
}
/**
* Initializes parameters for handling requests. This should only
* be used for advanced use-cases like implementing a plugin for
* integrating with an underluing server implementation.
* For a usage example, see `../../next/src/nextPlugin.rs`.
* @param p the parameters to initialize
* @returns initialized parameters
*/
initParams(p: Params) {
return p;
}
async loadEndpointTypeSchemas(endpoint: AnyEndpoint): Promise<void> {
if (
!endpoint.query &&
!endpoint.path &&
!endpoint.body &&
!endpoint.response
) {
if (!this.typeSchemas) {
throw new Error(
"Failed to provide `typeSchemas` to stl instance while using codegen schemas"
);
}
try {
const schemas = await this.typeSchemas[endpoint.endpoint]?.();
if (schemas) {
endpoint.path = schemas.path;
endpoint.query = schemas.query;
endpoint.body = schemas.body;
endpoint.response = schemas.response;
} else {
throw new Error(
"error encountered while handling endpoint " +
endpoint.endpoint +
": no schema found. run the `stl` cli on the project to generate the schema for the endpoint."
);
}
} catch (e) {
console.error(e);
}
}
}
/**
* Runs middleware and gets the parsed params to pass to an endpoint handler.
* This should not be called in typical use.
* It is primarily useful for implementing a plugin for
* integrating with an underluing server implementation.
* For a usage example, see `../../express/src/index.ts`.
* @param params request params
* @param context context with `stl` and request-specific data
* @returns a Promise that resolves to [request, context]
*/
async parseParams<EC extends AnyEndpoint>(
params: Params,
context: StlContext<EC>
): Promise<RequestData<EC["path"], EC["query"], EC["body"]>> {
return (await this.parseParamsWithContext(params, context))[0];
}
/**
* Runs middleware and gets the parsed params and context arguments to
* pass to an endpoint handler.
* This should not be called in typical use.
* It is primarily useful for implementing a plugin for
* integrating with an underluing server implementation.
* For a usage example, see `../../express/src/index.ts`.
* @param params request params
* @param context context with `stl` and request-specific data
* @returns a Promise that resolves to [request, context]
*/
async parseParamsWithContext<EC extends AnyEndpoint>(
params: Params,
context: StlContext<EC>
): Promise<
[RequestData<EC["path"], EC["query"], EC["body"]>, StlContext<EC>]
> {
await this.loadEndpointTypeSchemas(context.endpoint);
for (const plugin of Object.values(this.stainlessPlugins)) {
const middleware = plugin.middleware;
if (middleware) await middleware(params, context);
}
const parseParams = {
stlContext: context,
};
context.parsedParams = {
path: undefined,
query: undefined,
body: undefined,
};
try {
if (context.endpoint.query) {
context.endpoint[coercedQuery] ??= coerceParams(context.endpoint.query);
context.parsedParams.query = await context.endpoint[coercedQuery]
.parseAsync(params.query, parseParams)
.catch(prependZodPath("<query>"));
}
if (context.endpoint.path) {
context.endpoint[coercedPath] ??= coerceParams(context.endpoint.path);
context.parsedParams.path = await context.endpoint[coercedPath]
.parseAsync(params.path, parseParams)
.catch(prependZodPath("<path>"));
}
context.parsedParams.body = await context.endpoint.body
?.parseAsync(params.body, parseParams)
.catch(prependZodPath("<body>"));
} catch (error) {
if (error instanceof z.ZodError) {
let validationError = fromZodError(error).message;
if (validationError.startsWith("Validation error: ")) {
validationError = validationError.slice("Validation error: ".length);
}
throw new BadRequestError({
message: validationError,
issues: error.issues,
});
}
throw error;
}
const { query, path, body } = context.parsedParams;
return [{ ...path, ...query, ...body }, context] as any;
}
/**
* Handles an incoming request by invoking the endpoint for it.
* This should not be called in typical use.
* It is primarily useful for implementing a plugin for
* integrating with an underluing server implementation.
* For a usage example, see `../../next/src/nextPlugin.ts`.
* @param endpoint endpoint to handle incoming request
* @param params request params
* @param context context with `stl` and request-specific data
* @returns request response
*/
async execute<EC extends AnyEndpoint>(
params: Params,
context: StlContext<EC>
): Promise<ExtractExecuteResponse<EC>> {
const { endpoint } = context;
if (!endpoint.handler) {
throw new Error(`no endpoint handler defined`);
}
const [request, ctx] = await this.parseParamsWithContext(params, context);
const responseInput = await endpoint.handler(request, ctx);
const parseParams = {
stlContext: ctx,
};
const response = endpoint.response
? await endpoint.response.parseAsync(responseInput, parseParams)
: undefined;
return response;
}
/**
* Creates an endpoint.
*
* @param endpoint A string declaring the HTTP method and URL for this endpoint
* @param config optional configuration for the endpoint
* @param response optional schema of response, defaults to `z.void()`
* @param path optional schema of path params
* @param query optional schema of query params
* @param body optional schema of body params
* @param handler the function that handles requests to this endpoint
* @returns endpoint instance
*
* ## Example
* ```ts
* // ~/api/users/retrieve.ts
*
* export const retrieve = stl.endpoint({
* endpoint: "GET /api/users/{userId}",
* response: User,
* path: z.object({
* userId: z.string(),
* }),
* async handler({ userId }, ctx) {
* const user = await prisma.user.findUnique({
* where: {
* id: userId,
* },
* });
* if (!user) throw new NotFoundError();
* return user;
* },
* });
* ```
*/
endpoint<
MethodAndUrl extends HttpEndpoint,
Config extends EndpointConfig | undefined,
Path extends ZodObjectSchema | undefined,
Query extends ZodObjectSchema | undefined,
Body extends ZodObjectSchema | undefined,
Response extends z.ZodTypeAny = z.ZodVoid
>(
params: CreateEndpointOptions<
MethodAndUrl,
Config,
Path,
Query,
Body,
Response
>
): Endpoint<Config, MethodAndUrl, Path, Query, Body, Response> {
const { config, response, path, query, body, ...rest } = params;
return {
stl: this,
config: config as Config,
response: (response || z.void()) as Response,
path: path as Path,
query: query as Query,
body: body as Body,
...rest,
};
}
/**
* Creates a resource.
*
* @param models
* @param actions
* @param namespacedResources
* @param internal
* @param summary
* @returns resource instance
*
* ## Example
* ```ts
* // ~/api/posts/index.ts
*
* export const posts = stl.resource({
* summary: "Posts; the tweets of this twitter clone",
* internal: false,
* models: {
* Post,
* PostPage,
* PostSelection,
* },
* actions: {
* create,
* list,
* retrieve,
* },
* });
* ```
*/
resource<
Actions extends AnyActionsConfig | undefined,
Resources extends Record<string, ResourceConfig<any, any, any>> | undefined,
Models extends Record<string, z.ZodTypeAny> | undefined
>({
actions,
namespacedResources,
models,
...config
}: CreateResourceOptions<Actions, Resources, Models>): ResourceConfig<
Actions,
Resources,
Models
> {
return {
...config,
actions: actions || {},
namespacedResources: namespacedResources || {},
models: models || {},
} as ResourceConfig<Actions, Resources, Models>;
}
/**
* Creates a top-level API, which is composed primarily of resources
* and optionally an endpoint to retrieve an OpenAPI schema documenting
* the API.
*
* @param resources
* @param openapi
* @param topLevel
* @returns api instance
*
* ## Example
* ```ts
* // ~/api/index.ts
*
* import { stl } from "~/libs/stl";
* import { users } from "./users";
*
* export const api = stl.api({
* openapi: {
* endpoint: "GET /api/openapi",
* },
* resources: {
* users,
* },
* });
* ```
*/
api<
BasePath extends HttpPath,
TopLevel extends
| ResourceConfig<AnyActionsConfig, undefined, any>
| undefined = undefined,
Resources extends Record<string, AnyResourceConfig> | undefined = undefined
>({
basePath,
openapi,