assert

package
v0.0.0-...-dd0b383 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 10, 2024 License: BSD-3-Clause Imports: 2 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Assert

func Assert(is bool, msg string) string
Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/alextanhongpin/core/types/assert"
)

var (
	optional = assert.Optional
	required = assert.Required
	check    = assert.Assert
)

func main() {
	var req CreateOrderRequest
	req.Discount = -1
	req.LineItems = append(req.LineItems, LineItemRequest{Quantity: -1}, LineItemRequest{})
	b, err := json.MarshalIndent(req.Valid(), "", " ")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))

}

type CreateOrderRequest struct {
	Discount   int64
	LineItems  []LineItemRequest
	TotalPrice int64
}

func (req *CreateOrderRequest) Valid() map[string]string {
	res := map[string]string{
		"discount":   validateDiscount(req.Discount),
		"totalPrice": validatePrice(req.TotalPrice),
		"lineItems":  required(len(req.LineItems)),
	}

	for i, item := range req.LineItems {
		for k, v := range item.Valid() {
			res[fmt.Sprintf("lineItems[%d].%s", i, k)] = v
		}
	}

	return assert.Map(res)
}

type LineItemRequest struct {
	Price     int64
	ProductID string
	Quantity  int64
}

func (req *LineItemRequest) Valid() map[string]string {
	return assert.Map(map[string]string{
		"price":     validatePrice(req.Price),
		"productId": required(req.ProductID),
		"quantity":  validateQuantity(req.Quantity),
	})
}

func validatePrice(n int64) string {
	return required(n,
		check(n > 0, "must be greater than 0"))
}

func validateDiscount(n int64) string {
	return optional(n,
		check(n > 0, "must be greater than 0"),
		check(n <= 100, "maximum discount assert.Assert 100%"),
	)
}

func validateQuantity(n int64) string {
	return optional(n,
		check(n > 0, "must be greater than 0"))
}
Output:

{
 "discount": "must be greater than 0",
 "lineItems[0].price": "required, must be greater than 0",
 "lineItems[0].productId": "required",
 "lineItems[0].quantity": "must be greater than 0",
 "lineItems[1].price": "required, must be greater than 0",
 "lineItems[1].productId": "required",
 "totalPrice": "required, must be greater than 0"
}

func Map

func Map(kv map[string]string) map[string]string

func Optional

func Optional(v any, assertions ...string) string

func Required

func Required(v any, assertions ...string) string

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL