summaryrefslogtreecommitdiff
path: root/addons/reference/reference.go
blob: 66a20e06a69360314c3c0dd0372bb24f2a897afe (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
package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"text/template"

	"get"

	"github.com/bosssauce/ponzu/management/editor"
)

// Referenceable enures there is a way to reference the implenting type from
// within another type's editor and from type-scoped API calls
type Referenceable interface {
	Referenced() []byte
}

// Select returns the []byte of a <select> HTML element plus internal <options> with a label.
// IMPORTANT:
// The `fieldName` argument will cause a panic if it is not exactly the string
// form of the struct field that this editor input is representing
func Select(fieldName string, p interface{}, attrs map[string]string, contentType string, tmpl template.Template) []byte {
	// decode all content type from db into options map
	// map["?type=<contentType>&id=<id>"]t.String()
	options := make(map[string]string)

	var data []map[string]interface{}
	j := get.ContentAll(contentType)

	err := json.Unmarshal(j, data)
	if err != nil {
		return nil
	}

	for i := range data {
		k := fmt.Sprintf("?type=%s&id=%s", contentType, data[i]["id"].(string))
		v := &bytes.Buffer{}
		err := tmpl.Execute(v, data[i])
		if err != nil {
			return nil
		}

		options[k] = v.String()
	}

	return editor.Select(fieldName, p, attrs, options)
}