/
compiler.go
77 lines (64 loc) · 1.94 KB
/
compiler.go
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
67
68
69
70
71
72
73
74
75
76
77
package jsonschema
import (
"context"
"fmt"
"strings"
"github.com/metal-toolbox/governor-api/internal/models"
"github.com/santhosh-tekuri/jsonschema/v5"
"github.com/volatiletech/sqlboiler/v4/boil"
)
// Compiler is a struct for a JSON schema compiler
type Compiler struct {
jsonschema.Compiler
extensionID string
erdSlugPlural string
version string
}
// Option is a functional configuration option for JSON schema compiler
type Option func(c *Compiler)
// NewCompiler configures and creates a new JSON schema compiler
func NewCompiler(
extensionID, slugPlural, version string,
opts ...Option,
) *Compiler {
c := &Compiler{*jsonschema.NewCompiler(), extensionID, slugPlural, version}
c.Compiler.AssertFormat = true
c.Compiler.AssertContent = true
for _, opt := range opts {
opt(c)
}
return c
}
// WithUniqueConstraint enables the unique constraint extension for a JSON
// schema. An extra `unique` field can be added to the JSON schema, and the
// Validator will ensure that the combination of every properties in the
// array is unique within the given extension resource definition.
// Note that unique constraint validation will be skipped if db is nil.
func WithUniqueConstraint(
ctx context.Context,
extensionResourceDefinition *models.ExtensionResourceDefinition,
resourceID *string,
db boil.ContextExecutor,
) Option {
return func(c *Compiler) {
c.RegisterExtension(
"uniqueConstraint",
JSONSchemaUniqueConstraint,
&UniqueConstraintCompiler{extensionResourceDefinition, resourceID, ctx, db},
)
}
}
func (c *Compiler) schemaURL() string {
return fmt.Sprintf(
"https://governor/extensions/%s/erds/%s/%s/schema.json",
c.extensionID, c.erdSlugPlural, c.version,
)
}
// Compile compiles the schema string
func (c *Compiler) Compile(schema string) (*jsonschema.Schema, error) {
url := c.schemaURL()
if err := c.AddResource(url, strings.NewReader(schema)); err != nil {
return nil, err
}
return c.Compiler.Compile(url)
}