gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

util.go (1765B)


      1 package streams
      2 
      3 import (
      4 	"github.com/superseriousbusiness/activity/streams/vocab"
      5 )
      6 
      7 const (
      8 	// jsonLDContext is the key for the JSON-LD specification's context
      9 	// value. It contains the definitions of the types contained within the
     10 	// rest of the payload. Important for linked-data representations, but
     11 	// only applicable to go-fed at code-generation time.
     12 	jsonLDContext = "@context"
     13 )
     14 
     15 // Serialize adds the context vocabularies contained within the type
     16 // into the JSON-LD @context field, and aliases them appropriately.
     17 func Serialize(a vocab.Type) (m map[string]interface{}, e error) {
     18 	m, e = a.Serialize()
     19 	if e != nil {
     20 		return
     21 	}
     22 	v := a.JSONLDContext()
     23 	// Transform the map of vocabulary-to-aliases into a context payload,
     24 	// but do so in a way that at least keeps it readable for other humans.
     25 	var contextValue interface{}
     26 	if len(v) == 1 {
     27 		for vocab, alias := range v {
     28 			if len(alias) == 0 {
     29 				contextValue = vocab
     30 			} else {
     31 				contextValue = map[string]string{
     32 					alias: vocab,
     33 				}
     34 			}
     35 		}
     36 	} else {
     37 		var arr []interface{}
     38 		aliases := make(map[string]string)
     39 		for vocab, alias := range v {
     40 			if len(alias) == 0 {
     41 				arr = append(arr, vocab)
     42 			} else {
     43 				aliases[alias] = vocab
     44 			}
     45 		}
     46 		if len(aliases) > 0 {
     47 			arr = append(arr, aliases)
     48 		}
     49 		contextValue = arr
     50 	}
     51 	// TODO: Update the context instead if it already exists
     52 	m[jsonLDContext] = contextValue
     53 	// TODO: Sort the context based on arbitrary order.
     54 	// Delete any existing `@context` in child maps.
     55 	var cleanFnRecur func(map[string]interface{})
     56 	cleanFnRecur = func(r map[string]interface{}) {
     57 		for _, v := range r {
     58 			if n, ok := v.(map[string]interface{}); ok {
     59 				delete(n, jsonLDContext)
     60 				cleanFnRecur(n)
     61 			}
     62 		}
     63 	}
     64 	cleanFnRecur(m)
     65 	return
     66 }