src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

document.go (854B)


      1 package store
      2 
      3 import (
      4 	"encoding/json"
      5 	"fmt"
      6 	"os"
      7 	"time"
      8 )
      9 
     10 type Document struct {
     11 	Created time.Time       `json:"created"`
     12 	Id      string          `json:"id"`
     13 	Updated time.Time       `json:"updated"`
     14 	Data    json.RawMessage `json:"data"`
     15 
     16 	path string
     17 }
     18 
     19 func (d *Document) Update(v any) error {
     20 	data, err := json.MarshalIndent(v, "", "  ")
     21 	if err != nil {
     22 		return fmt.Errorf("failed to json marshal: %w", err)
     23 	}
     24 
     25 	d.Data = data
     26 	d.Updated = time.Now()
     27 
     28 	data, err = json.MarshalIndent(d, "", "  ")
     29 	if err != nil {
     30 		return fmt.Errorf("failed to json marshal: %w", err)
     31 	}
     32 
     33 	if err := os.WriteFile(d.path, data, fm); err != nil {
     34 		return fmt.Errorf("failed to write file %s: %w", d.path, err)
     35 	}
     36 
     37 	return nil
     38 }
     39 
     40 func (d *Document) Unmarshal(v any) error {
     41 	if err := json.Unmarshal(d.Data, v); err != nil {
     42 		return err
     43 	}
     44 
     45 	return nil
     46 }