summaryrefslogtreecommitdiff
path: root/vendor/github.com/go-fed/activity/streams/util.go
blob: ea27f2f9609f417547ce2efb7b8a0d2e67fbe7bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package streams

import (
	"github.com/go-fed/activity/streams/vocab"
)

const (
	// jsonLDContext is the key for the JSON-LD specification's context
	// value. It contains the definitions of the types contained within the
	// rest of the payload. Important for linked-data representations, but
	// only applicable to go-fed at code-generation time.
	jsonLDContext = "@context"
)

// Serialize adds the context vocabularies contained within the type
// into the JSON-LD @context field, and aliases them appropriately.
func Serialize(a vocab.Type) (m map[string]interface{}, e error) {
	m, e = a.Serialize()
	if e != nil {
		return
	}
	v := a.JSONLDContext()
	// Transform the map of vocabulary-to-aliases into a context payload,
	// but do so in a way that at least keeps it readable for other humans.
	var contextValue interface{}
	if len(v) == 1 {
		for vocab, alias := range v {
			if len(alias) == 0 {
				contextValue = vocab
			} else {
				contextValue = map[string]string{
					alias: vocab,
				}
			}
		}
	} else {
		var arr []interface{}
		aliases := make(map[string]string)
		for vocab, alias := range v {
			if len(alias) == 0 {
				arr = append(arr, vocab)
			} else {
				aliases[alias] = vocab
			}
		}
		if len(aliases) > 0 {
			arr = append(arr, aliases)
		}
		contextValue = arr
	}
	// TODO: Update the context instead if it already exists
	m[jsonLDContext] = contextValue
	// TODO: Sort the context based on arbitrary order.
	// Delete any existing `@context` in child maps.
	var cleanFnRecur func(map[string]interface{})
	cleanFnRecur = func(r map[string]interface{}) {
		for _, v := range r {
			if n, ok := v.(map[string]interface{}); ok {
				delete(n, jsonLDContext)
				cleanFnRecur(n)
			}
		}
	}
	cleanFnRecur(m)
	return
}