-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
246 lines (208 loc) · 6.78 KB
/
index.ts
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
import { getPathname } from '@graphql-ez/utils/url';
import type { EndpointOutput, RequestHandler } from '@sveltejs/kit';
import type { ResponseHeaders } from '@sveltejs/kit/types/helper';
import type { ServerRequest, ServerResponse } from '@sveltejs/kit/types/hooks';
import {
AppOptions,
BaseAppBuilder,
BuildAppOptions,
BuildContextArgs,
createEZAppFactory,
EZAppFactoryType,
GetEnvelopedFn,
handleRequest,
InternalAppBuildContext,
InternalAppBuildContextKey,
InternalAppBuildIntegrationContext,
LazyPromise,
ProcessRequestOptions,
PromiseOrValue,
} from 'graphql-ez';
import type { IncomingMessage } from 'http';
export interface EZAppBuilder extends BaseAppBuilder {
readonly buildApp: (options?: BuildAppOptions) => EZApp;
}
export * from 'graphql-ez';
export interface EZApp {
readonly handler: RequestHandler;
readonly getEnveloped: Promise<GetEnvelopedFn<unknown>>;
readonly ready: Promise<void>;
[InternalAppBuildContextKey]: InternalAppBuildContext;
}
export interface SvelteKitContextArgs<Locals = Record<string, any>, Body = unknown> extends BuildContextArgs {
sveltekit: {
req: ServerRequest<Locals, Body>;
responseHeaders: ResponseHeaders;
};
}
declare module 'graphql-ez' {
interface BuildContextArgs {
sveltekit?: {
req: ServerRequest<any, any>;
responseHeaders: ResponseHeaders;
};
}
interface InternalAppBuildIntegrationContext {
sveltekit?: SvelteKitHandlerContext;
}
}
export interface SvelteKitHandlerContext {
handlers: Array<(req: ServerRequest) => PromiseOrValue<ServerResponse | null | undefined | void>>;
}
export interface SvelteKitAppOptions extends AppOptions {
/**
* Build Context
*/
buildContext?: (args: any) => Record<string, unknown> | Promise<Record<string, unknown>>;
/**
* Customize some Helix processRequest options
*/
processRequestOptions?: <Locals = Record<string, any>, Body = unknown>(
req: ServerRequest<Locals, Body>
) => ProcessRequestOptions;
/**
* The path of where the EZ App is being served.
*
* If it's not specified, it's assumed that is should be served on any path.
*/
path?: string;
}
export function CreateApp(config: SvelteKitAppOptions = {}): EZAppBuilder {
const appConfig = { ...config };
const path = appConfig.path;
let ezApp: EZAppFactoryType;
try {
ezApp = createEZAppFactory(
{
integrationName: 'sveltekit',
},
appConfig
);
} catch (err) {
err instanceof Error && Error.captureStackTrace(err, CreateApp);
throw err;
}
const { appBuilder, onIntegrationRegister, ...commonApp } = ezApp;
const buildApp: EZAppBuilder['buildApp'] = function buildApp(buildOptions = {}) {
const { buildContext, onAppRegister, processRequestOptions } = appConfig;
let appHandler: RequestHandler | undefined;
const externalHandlers: SvelteKitHandlerContext['handlers'] = [];
const appPromise = Promise.allSettled([
appBuilder(buildOptions, async ({ ctx, getEnveloped }) => {
const integration: InternalAppBuildIntegrationContext = {
sveltekit: {
handlers: externalHandlers,
},
};
if (onAppRegister)
await onAppRegister({
ctx,
integration,
getEnveloped,
});
await onIntegrationRegister(integration);
const {
preProcessRequest,
options: { customHandleRequest },
} = ctx;
const requestHandler = customHandleRequest || handleRequest;
const hasHandlers = !!externalHandlers.length;
const EZHandler: RequestHandler = async function EZHandler(req) {
if (hasHandlers) {
const result = await Promise.all(externalHandlers.map(cb => cb(req)));
for (const response of result) if (response != null) return response;
}
if (path && getPathname(req.path) !== path) return;
const request = {
headers: req.headers,
method: req.method,
query: Object.fromEntries(req.query),
body: req.body,
};
const trapReq = new Proxy<IncomingMessage>(
{
headers: req.headers,
method: req.method,
} as IncomingMessage,
{
get(target, key) {
switch (key) {
case 'headers':
case 'method': {
return target[key];
}
}
throw Error('Property not available for SvelteKit');
},
}
);
const responseHeaders: NonNullable<EndpointOutput['headers']> = {};
return requestHandler<EndpointOutput>({
request,
req: trapReq,
getEnveloped,
baseOptions: appConfig,
contextArgs() {
return {
req: trapReq,
sveltekit: {
req,
responseHeaders,
},
};
},
buildContext,
onResponse(result) {
for (const { name, value } of result.headers) {
responseHeaders[name] = value;
}
return {
status: result.status,
body: result.payload as Record<string, any>,
headers: responseHeaders,
};
},
onMultiPartResponse() {
throw Error('Not supported for SvelteKit!');
},
onPushResponse() {
throw Error('Not supported for SvelteKit!');
},
preProcessRequest,
processRequestOptions: processRequestOptions && (() => processRequestOptions(req)),
});
};
return (appHandler = EZHandler);
}),
]).then(v => v[0]);
return {
handler: async function handler(req) {
if (appHandler) {
return appHandler(req);
}
const result = await appPromise;
if (result.status === 'rejected')
throw Error(
process.env.NODE_ENV === 'development'
? 'Error while building EZ App: ' + (result.reason?.message || JSON.stringify(result.reason))
: 'Unexpected Error'
);
return (await result.value.app)(req);
},
getEnveloped: LazyPromise(async () => {
const result = await appPromise;
if (result.status === 'rejected') throw result.reason;
return result.value.getEnveloped;
}),
ready: LazyPromise(async () => {
const result = await appPromise;
if (result.status === 'rejected') throw result.reason;
}),
[InternalAppBuildContextKey]: commonApp[InternalAppBuildContextKey],
};
};
return {
...commonApp,
buildApp,
};
}