Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot Marshal with top-level Meta #343

Open
ussu opened this issue Apr 4, 2022 · 1 comment
Open

Cannot Marshal with top-level Meta #343

ussu opened this issue Apr 4, 2022 · 1 comment

Comments

@ussu
Copy link

ussu commented Apr 4, 2022

Hi!

I could not find a way to easily to return a response with top-level custom metadata, i.e.

{
  "data": ...
  "meta": "my data"
}

but only found a way to add metadata at the resource level, e.g.

{
  "data": [
    {
      "meta": ...
    }
  ]
}

I had to write the following helper function to achieve it. is there a better way?

import (
	"encoding/json"
	"github.com/manyminds/api2go/jsonapi"
)

func MarshalWithMeta(data interface{}, meta map[string]interface{}) ([]byte, error) {
	document, err := jsonapi.MarshalToStruct(data, nil)
	if err != nil {
		return nil, err
	}

	document.Meta = meta
	bytesResponse, err := json.Marshal(document)
	if err != nil {
		return nil, err
	}

	return bytesResponse, nil
}
@irubnich
Copy link

irubnich commented Jun 7, 2022

I found this interface you can implement in the docs: https://pkg.go.dev/github.com/manyminds/api2go/jsonapi#MarshalMeta

So you can do it like this:

type Book struct {
  Id string
}

func (b Book) Meta() jsonapi.Meta {
  return jsonapi.Meta{
    "key": "value"
  }
}

and an instance will marshal into:

{
  "data": {
    "meta": {
      "key": "value"
    },
    "attributes": {
      "Id": "1"
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants