Search Apps Documentation Source Content File Folder Download Copy Actions Download

create.gno

1.70 Kb · 80 lines
 1package forms
 2
 3import (
 4	"chain/runtime"
 5	"time"
 6
 7	"gno.land/p/onbloc/json"
 8)
 9
10const dateFormat = "2006-01-02T15:04:05Z"
11
12func CreateField(label string, fieldType string, required bool) Field {
13	return Field{
14		Label:     label,
15		FieldType: fieldType,
16		Required:  required,
17	}
18}
19
20// CreateForm creates a new form with the given parameters
21func (db *FormDB) CreateForm(title string, description string, openAt string, closeAt string, data string) (string, error) {
22	// Parsing the dates
23	var parsedOpenTime, parsedCloseTime time.Time
24
25	if openAt != "" {
26		var err error
27		parsedOpenTime, err = time.Parse(dateFormat, openAt)
28		if err != nil {
29			return "", errInvalidDate
30		}
31	}
32
33	if closeAt != "" {
34		var err error
35		parsedCloseTime, err = time.Parse(dateFormat, closeAt)
36		if err != nil {
37			return "", errInvalidDate
38		}
39	}
40
41	// Parsing the json submission
42	node, err := json.Unmarshal([]byte(data))
43	if err != nil {
44		return "", errInvalidJson
45	}
46
47	fieldsCount := node.Size()
48	fields := make([]Field, fieldsCount)
49
50	// Parsing the json submission to create the gno data structures
51	for i := 0; i < fieldsCount; i++ {
52		field := node.MustIndex(i)
53
54		fields[i] = CreateField(
55			field.MustKey("label").MustString(),
56			field.MustKey("fieldType").MustString(),
57			field.MustKey("required").MustBool(),
58		)
59	}
60
61	// Generating the form ID
62	id := db.IDCounter.Next().String()
63
64	// Creating the form
65	form := Form{
66		ID:          id,
67		Owner:       runtime.CurrentRealm().Address(),
68		Title:       title,
69		Description: description,
70		CreatedAt:   time.Now(),
71		openAt:      parsedOpenTime,
72		closeAt:     parsedCloseTime,
73		Fields:      fields,
74	}
75
76	// Adding the form to the database
77	db.Forms = append(db.Forms, &form)
78
79	return id, nil
80}