api.spaceplanner.app

Spaceplanner API
git clone git://jacobedwards.org/api.spaceplanner.app
Log | Files | Refs

id.go (1893B)


      1 package backend
      2 
      3 import (
      4 	"encoding/json"
      5 	"errors"
      6 	"fmt"
      7 	"strconv"
      8 	"strings"
      9 )
     10 
     11 type ObjectType string
     12 
     13 type ObjectID struct {
     14 	Type ObjectType
     15 	Seq int64
     16 }
     17 
     18 var (
     19 	IDTypeFloorplan ObjectType = "flp"
     20 	IDTypePoint ObjectType = "pnt"
     21 	IDTypePointMap ObjectType = "pntmap"
     22 	IDTypeFurniture ObjectType = "fur"
     23 	IDTypeFurnitureMap ObjectType = "furmap"
     24 )
     25 
     26 var objectTypes []ObjectType
     27 
     28 func init() {
     29 	objectTypes = []ObjectType{
     30 		IDTypeFloorplan,
     31 		IDTypePoint,
     32 		IDTypePointMap,
     33 		IDTypeFurniture,
     34 		IDTypeFurnitureMap,
     35 	}
     36 }
     37 
     38 func ParseObjectID(s string) (ObjectID, error) {
     39 	a := strings.Split(s, "_")
     40 	if len(a) != 2 {
     41 		return ObjectID{}, errors.New(s + ": Invalid ID")
     42 	}
     43 
     44 	seq, err := strconv.ParseInt(a[1], 10, 64)
     45 	if err != nil {
     46 		return ObjectID{}, errors.New(s + ": Invalid ID (invalid sequence number)")
     47 	}
     48 
     49 	typ, err := objectType(a[0])
     50 	if err != nil {
     51 		return ObjectID{}, err
     52 	}
     53 	return makeID(typ, seq), nil
     54 }
     55 
     56 func makeID(typ ObjectType, seq int64) ObjectID {
     57 	return ObjectID{
     58 		Type: typ,
     59 		Seq: seq,
     60 	}
     61 }
     62 
     63 func objectType(typStr string) (ObjectType, error) {
     64 	typ := ObjectType(typStr)
     65 	for i := range objectTypes {
     66 		if typ == objectTypes[i] {
     67 			return typ, nil
     68 		}
     69 	}
     70 	return typ, errors.New(typStr + ": Invalid ID type")
     71 }
     72 
     73 func (o ObjectID) String() string {
     74 	return fmt.Sprintf("%s_%d", o.Type, o.Seq)
     75 }
     76 
     77 func (id ObjectID) MarshalJSON() ([]byte, error) {
     78 	return json.Marshal(id.String())
     79 }
     80 
     81 func (id *ObjectID) UnmarshalJSON(b []byte) error {
     82 	var s string
     83 	if err := json.Unmarshal(b, &s); err != nil {
     84 		return err
     85 	}
     86 	d, err := ParseObjectID(s)
     87 	*id = d
     88 	return err
     89 }
     90 
     91 func (id ObjectID) MarshalText() ([]byte, error) {
     92 	return []byte(id.String()), nil
     93 }
     94 
     95 func (id *ObjectID) UnmarshalText(b []byte) error {
     96 	d, err := ParseObjectID(string(b))
     97 	*id = d
     98 	return err
     99 }
    100 
    101 func (id *ObjectID) UnmarshalParam(p string) error {
    102 	return id.UnmarshalText([]byte(p))
    103 }