Go Swagger using map[string]interface{} as response - go

I'm trying to construct a Go Swagger response to my existing code without changing a bunch of it and I currently have:
// DataExpressionInput - only public so we can use it embedded in dataExpression
// swagger:model
type DataExpressionInput struct {
Name string `json:"name"`
Expression string `json:"expression"`
Type expressionType `json:"type"`
Comments string `json:"comments"`
Tags []string `json:"tags"`
}
// swagger:model dataExpressionModel
type DataExpression struct {
// The main data expression information
//
// Required: true
*DataExpressionInput
// Additional metadata
*pixlUser.APIObjectItem
}
//swagger:response dataExpressionLookup
type DataExpressionLookup map[string]DataExpression
I'm trying to return a dataExpressionLookup Object via my API but when I export the swagger definition i get:
"definitions": {
"DataExpressionInput": {
"description": "DataExpressionInput - only public so we can use it embedded in dataExpression",
"x-go-package": "github.com/pixlise/core/v2/core/expression"
},
"dataExpressionModel": {
"x-go-name": "DataExpression",
"x-go-package": "github.com/pixlise/core/v2/core/expression"
}
},
"responses": {
"dataExpressionLookup": {
"description": "",
"schema": {}
},
"deleteResponse": {
"description": "",
"schema": {}
},
"genericError": {
"description": "",
"schema": {}
},
"shareResponse": {
"description": "",
"schema": {}
}
},

Related

Define structure in golang

I am working on a project in which I receive payload data in the following format:
"name":"John",
"date":"2022-04-14",
"price":200,
"dependencies":[
{
"element_1":{
"items":[2,4],
"pricing":[1,2]
}
},
{
"element_2":{
"items":[5,4],
"pricing":[1,6]
}
}
]
How should I define the struct for this? If you know please let me know. Thanks!
This part
"dependencies":[
{
"element_1":{
"items":[2,4],
"pricing":[1,2]
}
},
{
"element_2":{
"items":[5,4],
"pricing":[1,6]
}
}
]
Looks like
type XXX struct {
Dependencies []map[string]Dependency `json:"dependencies"`
}
type Dependency struct {
Items []int // json…
Pricing []int // json…
}
But I am not sure… if element_x is dynamic or not. If it is predefined, ok.
If your json is
{
"name": "John",
"date": "2022-04-14",
"price": 200,
"dependencies":
[
{
"element_1":
{
"items":
[
2,
4
],
"pricing":
[
1,
2
]
}
},
{
"element_2":
{
"items":
[
5,
4
],
"pricing":
[
1,
6
]
}
}
]
}
Then you can create struct like this
type DemoStruct struct {
Name string `json:"name"`
Date string `json:"date"`
Price int64 `json:"price"`
Dependencies []Dependency `json:"dependencies"`
}
type Dependency struct {
Element1 *Element `json:"element_1,omitempty"`
Element2 *Element `json:"element_2,omitempty"`
}
type Element struct {
Items []int64 `json:"items"`
Pricing []int64 `json:"pricing"`
}

How to create a ResponseBody without an "entity" tag

I have built a controller which returns a list of objects
fun getUserCommunicationSettings(
#PathVariable commId: String,
#CommunicationTypeConstraint #RequestParam(required = false) commType: CommunicationType?
): ResponseEntity<out UserCommResponse> {
return communicationSettingsService.getUserCommSettings(commType, commId)
.mapError { mapUserCommErrorToResponse(it) }
.map { ResponseEntity.ok(SuccessResponse(it)) }
.fold<ResponseEntity<SuccessResponse<List<CommunicationSettingsDto>>>, ResponseEntity<ErrorResponse>, ResponseEntity<out UserCommResponse>>(
{ it },
{ it },
)
}
problem is it returns the following json with "entity" tag which i'd like to get rid of
{
"entity": [
{
"userId": "1075",
"userType": "CUSTOMER",
"communicationId": "972547784682",
"communicationType": "CALL",
"messageType": "CALL_COLLECTION"
}
]
}
any ideas?

how to create a struct/model in golang with dynamic/arbitrary fields

Is it possible to create a struct with dynamic/arbitrary fields and values?
My app will receive request with JSON body:
{
"Details": {
"Id": “123”,
},
"Event": {
"Event": "Event",
},
“RequestValues”: [
{
“Name": "Name1",
"Value": "Val1"
},
{
"Name": "Name2",
"Value": 2
},
{
"Name": “Foo”,
"Value": true
}
]
}
This will be unmarshalled to my model 'Request':
type Request struct {
Details Details `json:"Details"`
Event Event `json:"Event"`
RequestValues []RequestValues `json:"RequestValues"`
}
type Details struct {
Id string `json:"Id"`
}
type Event struct {
Event string `json:"Event"`
}
type RequestValues struct {
Name string `json:"Name"`
Value string `json:"Value"`
}
I have to re-map model 'Request' to a new model 'Event' with arbitrary fields in "Values". After marshalling new re- mapped model 'Event' I should get this JSON output that corresponds to the request:
{
"Event": "Event"
"Values": {
“Id": "123", <= non arbitrary mapping from Request.Detail.Id
"Name1": "Val1", <= arbitrary
"Name2": 2, <= arbitrary
“Foo”: true <= arbitrary
}
}
Arbitrary values will be mapped from "RequestValues". Names of those fields should be the values of Request.RequestValues.Name and their values should be the values of Request.RequestValues.Value
Here is my 'Event' model:
type Event struct {
Event string `json:"Event"`
Values Values `json:"Values"`
}
type Values struct{
Id string `json:"Id"`
}
Firstly, here's a JSON-valid copy of your JSON:
{
"Details": {
"Id": "123"
},
"Event": {
"Event": "Event"
},
"RequestValues": [
{
"RequestValueName": "Name1",
"RequestValue": "Val1"
},
{
"RequestValueName": "Name2",
"RequestValue": 2
},
{
"RequestValueName": "Foo",
"RequestValue": true
}
]
}
Start by creating a type Input struct{} to describe the JSON that you're looking to parse, and a type Output struct{} for the JSON that you're looking to generate, and write a little code to convert from one to the other. You don't have to add all of the fields right away - you can start with just Event for example and add more until you've got them all.
I've done this in https://play.golang.org/p/PvpKnFMrJjN to show you, but I would recommend having only a quick read of it before trying to recreate it yourself.
A useful tool to convert JSON into Go structs is https://mholt.github.io/json-to-go/ but it will trip on RequestValue in your example which has several data types (and is therefore where we use interface{}).
I thing that you can use map like this:
package main
import (
"fmt"
)
type Event struct {
event string
values map[string]string
}
func main() {
eventVar := Event{event: "event", values: map[string]string{}}
eventVar.values["Id"] = "12345"
eventVar.values["vale1"] = "value"
fmt.Println(eventVar)
}
You just need to validate somehow that the id it's in there, this if you need values in the same level.
I hope this works for you.

Get selection of non required field on introspection

I'm using GraphQL with Apollo Server and Client in JS and try to introspect my schema.
Simplified I have a schema like:
input LocationInput {
lat: Float
lon: Float
}
input CreateCityInput {
name: String!
location: LocationInput
}
I query this with an introspection like:
fragment InputTypeRef on __Type {
kind
name
ofType {
kind
name
inputFields {
name
type {
name
kind
ofType {
kind
name
inputFields {
name
type {
name
kind
}
}
}
}
}
}
}
query CreateCityInputFields {
input: __type(name: "CreateCityInput") {
inputFields {
name
description
type {
...InputTypeRef
}
}
}
}
As result I receive:
{
"data": {
"input": {
"inputFields": [
{
"name": "name",
"description": "",
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"inputFields": null
}
}
},
{
"name": "location",
"description": "",
"type": {
"kind": "INPUT_OBJECT",
"name": "LocationInput",
"ofType": null
}
}
]
}
}
}
As one can see: lat and lon are missing. If I set LocationInput as required (location: LocationInput!) in CreateCityInput I receive the missing lat and lon.
How can I query for lat and lon without haven LocationInput required?
Seems like I had a wrong query for the introspection. Moving the inputField part out of ofType to the upper level fix the issue:
kind
name
inputFields {
name
description
type {
kind
name
ofType {
kind
name
}
}
}
ofType {
kind
name
inputFields {
name
description
type {
kind
name
ofType {
kind
name
}
}
}
}
}
query CreateCityInputFields {
input: __type(name: "CreateCityInput") {
inputFields {
name
description
type {
...InputTypeRef
}
}
}
}
Solved the issue.

GraphQL Mutation with JSON Patch

Are there any data types in GraphQL that can be used to describe a JSON Patch operation?
The structure of a JSON Patch operation is as follows.
{ "op": "add|replace|remove", "path": "/hello", "value": ["world"] }
Where value can be any valid JSON literal or object, such as.
"value": { "name": "michael" }
"value": "hello, world"
"value": 42
"value": ["a", "b", "c"]
op and path are always simple strings, value can be anything.
If you need to return JSON type then graphql have scalar JSON
which return any JSON type where you want to return it.
Here is schema
`
scalar JSON
type Response {
status: Boolean
message: String
data: JSON
}
type Test {
value: JSON
}
type Query {
getTest: Test
}
type Mutation {
//If you want to mutation then pass data as `JSON.stringify` or json formate
updateTest(value: JSON): Response
}
`
In resolver you can return anything in json format with key name "value"
//Query resolver
getTest: async (_, {}, { context }) => {
// return { "value": "hello, world" }
// return { "value": 42 }
// return { "value": ["a", "b", "c"] }
// return anything in json or string
return { "value": { "name": "michael" } }
},
// Mutation resolver
async updateTest(_, { value }, { }) {
// Pass data in JSON.stringify
// value : "\"hello, world\""
// value : "132456"
// value : "[\"a\", \"b\", \"c\"]"
// value : "{ \"name\": \"michael\" }"
console.log( JSON.parse(value) )
//JSON.parse return formated required data
return { status: true,
message: 'Test updated successfully!',
data: JSON.parse(value)
}
},
the only thing you need to specifically return "value" key to identify to get in query and mutation
Query
{
getTest {
value
}
}
// Which return
{
"data": {
"getTest": {
"value": {
"name": "michael"
}
}
}
}
Mutation
mutation {
updateTest(value: "{ \"name\": \"michael\" }") {
data
status
message
}
}
// Which return
{
"data": {
"updateTest": {
"data": null,
"status": true,
"message": "success"
}
}
}

Resources