d-exclaimation/pioneer

Set some to the response

Closed this issue · 9 comments

How can I add something to the response? For example, I need to add cookies

The Vapor request and response object are given as parameter to the context builder in the Pioneer initiator (more details here). You can use that to create a Context struct that contains the request specific response (An example of context builder)

From there you can grab the context from the resolver and get the response object used to make the GraphQL response.

It should look and work similarly to apollo-server-express

I did that, but how do I add cookies for example in the response of the Users function?

The Response object should have the cookies property (Response's cookie). You can just add the cookie manually by mutating that cookies if I am not mistaken (HTTPCookies object have subscript method that handle setting values)

An example would look like

let cookie = HTTPCookies.Value(string: "some-value", expires: expiryDate, maxAge: 300, isSecure: false, isHTTPOnly: true, sameSite: HTTPCookies.SameSitePolicy.none)
response.cookies["cookie-name"] = cookie

I know how to add cookies to the response. Explain how I can add cookies to the response that is in the context of the users function. In the users function, I return the type [User] and not Response

in this case, the function createCookies returns a response with a cookie. How can i return a ClientTokenReponse so that there are cookies in the header?
Bildschirmfoto 2022-05-18 um 19 39 02

You can't reassigned the response object with your own. You have to use the response given.

You can do something like

context.response.cookies["my-cookie"] = ...

but not

context.response = ...

In the users function example you give, the code would look like

func users(ctx: Context, _: NoArguments) async -> [User] {
    ctx.response.cookies["refresh-token"] = /* refresh token */
    ctx.response.cookies["access-token"] = /* access token */
    return await getUsers()
}

The response object given in the context builder is going to be the one used to respond to the request. You don't need to return it, just mutate its values (it's a class so its values can be mutated)

There is currently no way for a resolver function to return a custom response. The schema library Graphiti only take functions that return the type describe in the schema, and this library also have to handle encoding the returned value into a response that follow the proper GraphQL format.

Thank you very much, everything is clear now