svelte-add / graphql-server

⚠️ MOVED: https://github.com/svelte-add/svelte-add/ ⚠️ (out of date) A command to add a GraphQL server to your Svelte project
MIT License
31 stars 1 forks source link

fixed headers issue #6

Closed MirrorBytes closed 3 years ago

MirrorBytes commented 3 years ago

Without this, the headers are not properly set. You get a response header that looks like this instead:

0: [object Object]
babichjacob commented 3 years ago

Great, thanks!

babichjacob commented 3 years ago

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.

MirrorBytes commented 3 years ago

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.

MirrorBytes commented 3 years ago

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.