Skip to content

Commit

Permalink
it's working yay!
Browse files Browse the repository at this point in the history
  • Loading branch information
matronator committed Apr 6, 2024
1 parent 6a4ee62 commit 1a28cc6
Show file tree
Hide file tree
Showing 11 changed files with 396 additions and 96 deletions.
6 changes: 4 additions & 2 deletions .amock.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
"host": "localhost",
"port": 8000,
"entities": [
"user.json"
]
"user.json",
"post.json"
],
"initCount": 1
}
68 changes: 57 additions & 11 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"log"
"os"
"path"
"strings"
"time"

"github.com/jwalton/gchalk"
Expand All @@ -16,21 +17,34 @@ func GenerateEntity(entity EntityJSON, table *Table) (Entity, *Table) {
fields := make(Entity, len(entity))

for key, value := range entity {
fields[key], table = GenerateField(value, table)
options := FieldOptions{false, false, false}
fieldName := key

if strings.HasSuffix(key, "!") {
options.Required = true
fieldName = strings.TrimSuffix(key, "!")
} else if strings.HasSuffix(key, "?") {
options.Nullable = true
fieldName = strings.TrimSuffix(key, "?")
} else if strings.HasSuffix(key, "[]") {
options.Children = true
fieldName = strings.TrimSuffix(key, "[]")
}
fields[fieldName], table = GenerateField(fieldName, value, table, options)
}

return fields, table
}

func HydrateDatabase(db Database) Database {
func HydrateDatabase(db *Database) *Database {
now := time.Now()
Debug("Building database...")

var entityJSON EntityJSON

for key, table := range db.Tables {
updated := CreateTable(&table, entityJSON)
db.Tables[key] = updated
db.Tables[key] = *updated
}

elapsed := time.Since(now).String()
Expand All @@ -39,18 +53,33 @@ func HydrateDatabase(db Database) Database {
return db
}

func CreateTable(table *Table, entityJSON EntityJSON) Table {
func CreateTable(table *Table, entityJSON EntityJSON) *Table {
filename := table.Name + ".amock.json"
dir := path.Join(DataDir, filename)
schemaDir := path.Join(SchemaDir, table.Name+".amock.schema.json")

if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) {
table.File = dir
Debug("Table "+gchalk.Bold(table.Name)+" found at "+gchalk.Italic(dir)+" - skipping...", "table", table.Name, "file", dir)

return *table
if _, err = os.Stat(schemaDir); !errors.Is(err, os.ErrNotExist) {
Debug("Table "+gchalk.Bold(table.Name)+" found at "+gchalk.Italic(dir)+" - skipping...", "table", table.Name, "file", dir, "schema", schemaDir)
table.File = dir
table.SchemaFile = schemaDir

var schema []byte
schema, err = os.ReadFile(table.SchemaFile)
if err != nil {
log.Fatal(err)
}

err = json.Unmarshal(schema, &table.Definition)
if err != nil {
log.Fatal(err)
}

return table
}
}

raw, err := os.ReadFile(table.Definition)
raw, err := os.ReadFile(table.DefinitionFile)

if err != nil {
log.Fatal(err)
Expand All @@ -67,15 +96,18 @@ func CreateTable(table *Table, entityJSON EntityJSON) Table {
entities[i], table = GenerateEntity(entityJSON, table)
}

schema, _ := json.Marshal(table.Definition)
_ = os.WriteFile(schemaDir, schema, os.ModePerm)

b, _ := json.Marshal(entities)

_ = os.WriteFile(dir, b, os.ModePerm)

table.File = dir

Debug("Table "+gchalk.Bold(table.Name)+" created at "+gchalk.Italic(dir)+" from file "+gchalk.Bold(table.Definition), "table", table.Name, "file", dir, "schema", table.Definition)
Debug("Table "+gchalk.Bold(table.Name)+" created at "+gchalk.Italic(dir)+" from file "+gchalk.Bold(table.DefinitionFile), "table", table.Name, "file", dir, "schema", table.DefinitionFile)

return *table
return table
}

func GetTable(table *Table) ([]byte, error) {
Expand Down Expand Up @@ -116,3 +148,17 @@ func WriteTable(table *Table, collection EntityCollection) error {

return err
}

func AppendTable(table *Table, entity Entity) error {
collection, err := ReadTable(table)

if err != nil {
return err
}

collection = append(collection, entity)

err = WriteTable(table, collection)

return err
}
66 changes: 44 additions & 22 deletions generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,37 @@ var FieldPattern = regroup.MustCompile(`(?P<type>[a-z]+)(?P<subtype>\.[a-z]+)?(?
var NumberRangePattern = regroup.MustCompile(`(?P<min>(-?[0-9]+(\.[0-9]+)?)|x)?-(?P<max>(-?[0-9]+(\.[0-9]+)?)|x)?`)

type Field struct {
Type string `regroup:"type"`
Subtype string `regroup:"subtype"`
Params string `regroup:"params"`
Type string `regroup:"type" json:"type"`
Subtype string `regroup:"subtype" json:"subtype"`
Params string `regroup:"params" json:"params"`
Required bool `json:"required"`
Nullable bool `json:"nullable"`
}

func GenerateField(field string, table *Table) (any, *Table) {
f := &Field{}
type FieldOptions struct {
Required bool
Nullable bool
Children bool
}

err := FieldPattern.MatchToTarget(field, f)
func GenerateField(fieldName string, field string, table *Table, options FieldOptions) (any, *Table) {
f := *GetFieldType(field)
f.Required = options.Required
f.Nullable = options.Nullable
table.Definition[fieldName] = &f

if err != nil {
panic(err)
}
return GenerateEntityField(f, table)
}

var subtype, paramStr string
func GenerateEntityField(field Field, table *Table) (any, *Table) {
gen := GetGenerator(field.Type, field.Subtype)
var paramStr string
var params []string
var gen any

t := f.Type
if len(f.Subtype) > 1 {
subtype = strings.TrimLeft(f.Subtype, ".")
}

gen = GetGenerator(t, subtype)
if len(field.Params) > 1 {
paramStr = strings.TrimLeft(field.Params, ":")

if len(f.Params) > 1 {
paramStr = strings.TrimLeft(f.Params, ":")

if f.Type == "number" {
if field.Type == "number" {
params = strings.Split(paramStr, ",")
for i, p := range params {
if strings.Contains(p, "-") {
Expand All @@ -57,7 +59,7 @@ func GenerateField(field string, table *Table) (any, *Table) {
} else {
params = strings.Split(paramStr, ",")
}
} else if f.Type == "id" && subtype != "uuid" {
} else if field.Type == "id" && field.Subtype != "uuid" {
params = []string{strconv.Itoa(int(table.LastAutoID))}
table.LastAutoID = table.LastAutoID + 1
}
Expand All @@ -73,6 +75,26 @@ func GenerateField(field string, table *Table) (any, *Table) {
return reflect.ValueOf(gen).Call([]reflect.Value{})[0].Interface(), table
}

func GetFieldType(field string) *Field {
f := &Field{}

err := FieldPattern.MatchToTarget(field, f)

if err != nil {
panic(err)
}

var subtype string

if len(f.Subtype) > 1 {
subtype = strings.TrimLeft(f.Subtype, ".")
}

f.Subtype = subtype

return f
}

type GeneratorFunc any

type GeneratorMap map[string]GeneratorFunc
Expand Down
31 changes: 21 additions & 10 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func LogRequest(next http.Handler) http.Handler {
log.SetPrefix("[amock]: ")

remoteAddr := gchalk.Bold(r.RemoteAddr)
method := requestMethodColor(r.Method)
method := RequestMethodColor(r.Method, true)
recorder := &StatusRecorder{w, http.StatusOK}

next.ServeHTTP(recorder, r)
Expand All @@ -71,26 +71,37 @@ func LogRequest(next http.Handler) http.Handler {
})
}

func requestMethodColor(m string) string {
var method string
func RequestMethodColor(m string, inverse bool) string {
method := m

if inverse {
method = " " + m + " "
}

switch m {
case http.MethodGet:
method = gchalk.WithBrightWhite().WithBold().BgBrightBlue(" " + m + " ")
method = gchalk.WithBold().BrightBlue(method)
case http.MethodPost:
method = gchalk.WithBrightWhite().WithBold().BgBrightGreen(" " + m + " ")
method = gchalk.WithBold().BrightGreen(method)
case http.MethodPut:
method = gchalk.WithBrightWhite().WithBold().BgBrightYellow(" " + m + " ")
method = gchalk.WithBold().BrightYellow(method)
case http.MethodPatch:
method = gchalk.WithBrightWhite().WithBold().BgBrightCyan(" " + m + " ")
method = gchalk.WithBold().BrightCyan(method)
case http.MethodDelete:
method = gchalk.WithBrightWhite().WithBold().BgRed(" " + m + " ")
method = gchalk.WithBold().Red(method)
case http.MethodOptions:
method = gchalk.WithBrightWhite().WithBold().BgBlue(" " + m + " ")
method = gchalk.WithBold().Blue(method)
case http.MethodHead:
method = gchalk.WithBrightWhite().WithBold().BgMagenta(" " + m + " ")
method = gchalk.WithBold().Magenta(method)
default:
method = m
}

if inverse {
method = gchalk.BgBrightWhite(method)
method = gchalk.Inverse(method)
}

return method
}

Expand Down
Loading

0 comments on commit 1a28cc6

Please sign in to comment.