I am using Lighthouse GraphQL with Laravel 9 for my application. Graphql have standard format and each response show under the data and operation name. It does not show proper response (error/success) to handle for front-end application. Because, on the basis of error code iOS/Android/frontend may work easily. Here is the sample:
Request:
query Translations {
translations {
name
slug
}
}
Response:
{
"data": {
"translations": [
{
"name": "English",
"slug": "en_US"
},
{
"name": "English (United Kingdom)",
"slug": "en_UK"
}
]
}
}
I have tried to override response with Laravel response classes and create custom queries/mutations resolver. But, it returns all the information. This should use Graphql "Tailoring your need" also. So, I want to customize the response so that response should include code, status, message, data[].
The result I got:
{
"status": true,
"code": 200,
"message": "",
"data": [
{
"_id": "63b2d767e2a07754b20845f6",
"name": "English",
"slug": "en_US",
"isActive": true,
"isDefault": true,
"updated_at": "2023-01-02T13:08:54.940000Z",
"created_at": "2023-01-02T13:08:54.940000Z",
"logo": "/United-States.svg"
},
{
"_id": "63b3e78ae2a07754b20845ff",
"name": "English (United Kingdom)",
"slug": "en_UK",
"isActive": true,
"isDefault": false,
"updated_at": "2023-01-03T08:30:02.085000Z",
"created_at": "2023-01-03T08:30:02.085000Z",
"logo": "/Great-Britain.svg"
}
]
}
It should be:
{
"status": true,
"code": 200,
"message": "",
"data": [
{
"name": "English",
"slug": "en_US"
},
{
"name": "English (United Kingdom)",
"slug": "en_UK"
}
]
}
2
Answers
Lighthouse returns the response based on the GraphQL specification. You have the power to change the response with the EndRequest event. Listen to the event in
AppServiceProvider
and then manipulate the response in any form that you need.I would strongly advise against this, as it violates the GraphQL specification:
Use
extensions
for custom additions. You can add to extensions in Lighthouse by listening to theBuildExtensionsResponse
event, see https://lighthouse-php.com/master/api-reference/events.html#buildextensionsresponse