Closed MirrorBytes closed 3 years ago
Great, thanks!
How do you get output headers from your GraphQL server / schema / resolvers? I want to test reducing this down to
const headers = {};
for (const { name, value } of result.headers) {
headers[name] = value;
}
but don't know how to verify it works for sure.
This would definitely work, I just avoided the for..of loop due to eslint throwing annoying errors. I'll setup a repo later as an example, but I found this issue when trying to set cookies.
I use this class for cookie handling (seemed to be the easiest way to ensure they were properly set in resolvers):
class Cookies {
public cookies: string[] = [];
set(name: string, value: string, options: Record<string, unknown>): void {
const keys = Object.keys(options);
const conOptions = keys.map((key) => `${key}=${options[key]}`);
this.cookies.push(`${name}=${value}; ${conOptions.join(';')}`);
}
}
And funnel it into my resolvers using context:
const cookies = new Cookies();
const parameters = getGraphQLParameters(request);
const result = await processRequest({
...parameters,
// For example, auth information is put in context for the resolver
contextFactory: (): Context => ({
req: request,
cookies
}),
request,
schema
});
if (result.type === 'RESPONSE') {
if (cookies.cookies.length > 0) {
result.headers.push({ name: 'Set-Cookie', value: cookies.cookies[0] });
}
const headers = {};
for (const { name, value } of result.headers) {
headers[name] = value;
}
return {
body: result.payload,
headers,
status: result.status
};
}
Essentially, prior to this merge, no headers were actually set due to the type difference of result.headers
from graphql-helix
and SvelteKit's Headers
type.
In fact, I messed up a bit here. The headers reassignment should be within the RESPONSE
conditional. I'll create another pull request with the corrected info along with the example repo.
Without this, the headers are not properly set. You get a response header that looks like this instead: