/
index.ts
175 lines (161 loc) · 4.58 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
import type {
APIContext,
AstroConfig,
AstroMiddlewareInstance,
EndpointHandler,
EndpointOutput,
MiddlewareEndpointHandler,
Params,
} from '../../@types/astro';
import type { Environment, RenderContext } from '../render/index';
import { isHybridOutput } from '../../prerender/utils.js';
import { renderEndpoint } from '../../runtime/server/index.js';
import { ASTRO_VERSION } from '../constants.js';
import { AstroCookies, attachToResponse } from '../cookies/index.js';
import { AstroError, AstroErrorData } from '../errors/index.js';
import { warn, type LogOptions } from '../logger/core.js';
import { callMiddleware } from '../middleware/callMiddleware.js';
import { isValueSerializable } from '../render/core.js';
const clientAddressSymbol = Symbol.for('astro.clientAddress');
const clientLocalsSymbol = Symbol.for('astro.locals');
type EndpointCallResult =
| {
type: 'simple';
body: string;
encoding?: BufferEncoding;
cookies: AstroCookies;
}
| {
type: 'response';
response: Response;
};
export function createAPIContext({
request,
params,
site,
props,
adapterName,
}: {
request: Request;
params: Params;
site?: string;
props: Record<string, any>;
adapterName?: string;
}): APIContext {
const context = {
cookies: new AstroCookies(request),
request,
params,
site: site ? new URL(site) : undefined,
generator: `Astro v${ASTRO_VERSION}`,
props,
redirect(path, status) {
return new Response(null, {
status: status || 302,
headers: {
Location: path,
},
});
},
url: new URL(request.url),
get clientAddress() {
if (!(clientAddressSymbol in request)) {
if (adapterName) {
throw new AstroError({
...AstroErrorData.ClientAddressNotAvailable,
message: AstroErrorData.ClientAddressNotAvailable.message(adapterName),
});
} else {
throw new AstroError(AstroErrorData.StaticClientAddressNotAvailable);
}
}
return Reflect.get(request, clientAddressSymbol);
},
} as APIContext;
// We define a custom property, so we can check the value passed to locals
Object.defineProperty(context, 'locals', {
get() {
return Reflect.get(request, clientLocalsSymbol);
},
set(val) {
if (typeof val !== 'object') {
throw new AstroError(AstroErrorData.LocalsNotAnObject);
} else {
Reflect.set(request, clientLocalsSymbol, val);
}
},
});
return context;
}
export async function callEndpoint<MiddlewareResult = Response | EndpointOutput>(
mod: EndpointHandler,
env: Environment,
ctx: RenderContext,
logging: LogOptions,
middleware?: AstroMiddlewareInstance<MiddlewareResult> | undefined
): Promise<EndpointCallResult> {
const context = createAPIContext({
request: ctx.request,
params: ctx.params,
props: ctx.props,
site: env.site,
adapterName: env.adapterName,
});
let response;
if (middleware && middleware.onRequest) {
const onRequest = middleware.onRequest as MiddlewareEndpointHandler;
response = await callMiddleware<Response | EndpointOutput>(
env.logging,
onRequest,
context,
async () => {
if (env.mode === 'development' && !isValueSerializable(context.locals)) {
throw new AstroError({
...AstroErrorData.LocalsNotSerializable,
message: AstroErrorData.LocalsNotSerializable.message(ctx.pathname),
});
}
return await renderEndpoint(mod, context, env.ssr);
}
);
} else {
response = await renderEndpoint(mod, context, env.ssr);
}
if (response instanceof Response) {
attachToResponse(response, context.cookies);
return {
type: 'response',
response,
};
}
if (env.ssr && !ctx.route?.prerender) {
if (response.hasOwnProperty('headers')) {
warn(
logging,
'ssr',
'Setting headers is not supported when returning an object. Please return an instance of Response. See https://docs.astro.build/en/core-concepts/endpoints/#server-endpoints-api-routes for more information.'
);
}
if (response.encoding) {
warn(
logging,
'ssr',
'`encoding` is ignored in SSR. To return a charset other than UTF-8, please return an instance of Response. See https://docs.astro.build/en/core-concepts/endpoints/#server-endpoints-api-routes for more information.'
);
}
}
return {
type: 'simple',
body: response.body,
encoding: response.encoding,
cookies: context.cookies,
};
}
function isRedirect(statusCode: number) {
return statusCode >= 300 && statusCode < 400;
}
export function throwIfRedirectNotAllowed(response: Response, config: AstroConfig) {
if (config.output !== 'server' && !isHybridOutput(config) && isRedirect(response.status)) {
throw new AstroError(AstroErrorData.StaticRedirectNotAvailable);
}
}