feat: initialize CollabTableServer with models, sync, and notification handling
- Add go.mod and go.sum for dependency management - Implement models for List, Field, Item, ItemValue, SyncRequest, SyncResponse, and NotificationEvent - Create notification handling functions including enqueueNotification and ignoreNotificationError - Implement sync functionality to handle data synchronization between client and server - Add web data handling and notification polling endpoints - Include tests for timestamp normalization and sync logic - Embed web assets for serving the frontend application
This commit is contained in:
1 parent
e12940fef0
commit
cac2faae2e
41 files changed
+2535
-5502
No files matched your search
@@ -0,0 +1,640 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(...any) error
|
||||
}
|
||||
|
||||
func scanList(row rowScanner) (List, error) {
|
||||
var list List
|
||||
var deleted int
|
||||
err := row.Scan(&list.ID, &list.Name, &list.CreatedAt, &list.UpdatedAt, &deleted)
|
||||
list.IsDeleted = deleted != 0
|
||||
return list, err
|
||||
}
|
||||
|
||||
func scanField(row rowScanner) (Field, error) {
|
||||
var field Field
|
||||
var deleted int
|
||||
err := row.Scan(
|
||||
&field.ID,
|
||||
&field.Name,
|
||||
&field.FieldType,
|
||||
&field.FieldOptions,
|
||||
&field.Alignment,
|
||||
&field.ListID,
|
||||
&field.Order,
|
||||
&field.CreatedAt,
|
||||
&field.UpdatedAt,
|
||||
&deleted,
|
||||
)
|
||||
field.IsDeleted = deleted != 0
|
||||
return field, err
|
||||
}
|
||||
|
||||
func scanItem(row rowScanner) (Item, error) {
|
||||
var item Item
|
||||
var deleted int
|
||||
err := row.Scan(&item.ID, &item.ListID, &item.CreatedAt, &item.UpdatedAt, &deleted)
|
||||
item.IsDeleted = deleted != 0
|
||||
return item, err
|
||||
}
|
||||
|
||||
func scanItemValue(row rowScanner) (ItemValue, error) {
|
||||
var value ItemValue
|
||||
err := row.Scan(&value.ID, &value.ItemID, &value.FieldID, &value.Value, &value.UpdatedAt)
|
||||
return value, err
|
||||
}
|
||||
|
||||
const listColumns = `id, name, createdat, updatedat, COALESCE(isdeleted, 0)`
|
||||
const fieldColumns = `id, name, fieldtype, COALESCE(fieldoptions, ''), COALESCE(alignment, 'start'), listid, "order", createdat, updatedat, COALESCE(isdeleted, 0)`
|
||||
const itemColumns = `id, listid, createdat, updatedat, COALESCE(isdeleted, 0)`
|
||||
const valueColumns = `id, itemid, fieldid, COALESCE(value, ''), updatedat`
|
||||
|
||||
func (d *DB) getList(ctx context.Context, id string) (List, error) {
|
||||
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64) ([]List, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 1)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
conditions = append(conditions, "updatedat >= $1")
|
||||
args = append(args, *since)
|
||||
}
|
||||
query := `SELECT ` + listColumns + ` FROM lists`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat DESC"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
lists := make([]List, 0)
|
||||
for rows.Next() {
|
||||
list, err := scanList(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lists = append(lists, list)
|
||||
}
|
||||
return lists, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
if listID != "" {
|
||||
args = append(args, listID)
|
||||
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + fieldColumns + ` FROM fields`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += ` ORDER BY "order" ASC`
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
fields := make([]Field, 0)
|
||||
for rows.Next() {
|
||||
field, err := scanField(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = append(fields, field)
|
||||
}
|
||||
return fields, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
if listID != "" {
|
||||
args = append(args, listID)
|
||||
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + itemColumns + ` FROM items`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat DESC"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]Item, 0)
|
||||
for rows.Next() {
|
||||
item, err := scanItem(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]ItemValue, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 2)
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
if itemID != "" {
|
||||
args = append(args, itemID)
|
||||
conditions = append(conditions, fmt.Sprintf("itemid = $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + valueColumns + ` FROM item_values`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat ASC"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]ItemValue, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanItemValue(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func requestDeviceID(r *http.Request, bodyValue string) string {
|
||||
if value := strings.TrimSpace(r.Header.Get("X-Device-Id")); value != "" {
|
||||
return value
|
||||
}
|
||||
if value := strings.TrimSpace(r.URL.Query().Get("deviceId")); value != "" {
|
||||
return value
|
||||
}
|
||||
return strings.TrimSpace(bodyValue)
|
||||
}
|
||||
|
||||
func boolInt(value bool) int {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type listMutation struct {
|
||||
List
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, lists)
|
||||
return
|
||||
}
|
||||
|
||||
var request listMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.Name == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
||||
list, err := s.db.getList(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
list, err := s.db.getList(r.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
if err != nil || list.IsDeleted {
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch list")
|
||||
} else {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
case http.MethodPut:
|
||||
var request struct {
|
||||
Name string `json:"name"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
||||
list, err := s.db.getList(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
case http.MethodDelete:
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete list")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
||||
writeJSON(w, http.StatusOK, map[string]string{"message": "List deleted successfully"})
|
||||
}
|
||||
}
|
||||
|
||||
type fieldMutation struct {
|
||||
Field
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
||||
fields, err := s.db.queryFields(r.Context(), false, nil, r.PathValue("listId"))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, fields)
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request fieldMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" || request.Name == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Field id, listId, and name are required")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
field, err := s.getField(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, field)
|
||||
}
|
||||
|
||||
func (s *Server) getField(ctx context.Context, id string) (Field, error) {
|
||||
return scanField(s.db.pool.QueryRow(ctx, `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
switch r.Method {
|
||||
case http.MethodPut:
|
||||
var request struct {
|
||||
Name string `json:"name"`
|
||||
FieldType string `json:"fieldType"`
|
||||
FieldOptions string `json:"fieldOptions"`
|
||||
Alignment string `json:"alignment"`
|
||||
Order int `json:"order"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `
|
||||
UPDATE fields
|
||||
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
||||
WHERE id = $7
|
||||
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||
return
|
||||
}
|
||||
field, err := s.getField(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, field)
|
||||
case http.MethodDelete:
|
||||
var request struct {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
_ = decodeJSON(r, &request) // DELETE bodies are optional.
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
var field Field
|
||||
cascade := false
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
var err error
|
||||
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
var remaining int
|
||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining == 0 {
|
||||
cascade = true
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete field")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"message": "Field deleted successfully", "cascadeItemsDeleted": cascade})
|
||||
}
|
||||
}
|
||||
|
||||
type itemMutation struct {
|
||||
Item
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
||||
listID := r.PathValue("listId")
|
||||
if listID == "" {
|
||||
parts := strings.Split(strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/"), "/")
|
||||
if len(parts) == 2 && parts[0] == "list" {
|
||||
listID = parts[1]
|
||||
}
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), false, nil, listID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, items)
|
||||
}
|
||||
|
||||
func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request itemMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
item, err := s.getItem(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, item)
|
||||
}
|
||||
|
||||
func (s *Server) getItem(ctx context.Context, id string) (Item, error) {
|
||||
return scanItem(s.db.pool.QueryRow(ctx, `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Server) handleValuesForItem(w http.ResponseWriter, r *http.Request) {
|
||||
itemID := r.PathValue("itemId")
|
||||
if itemID == "" {
|
||||
parts := strings.Split(strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/"), "/")
|
||||
if len(parts) == 2 && parts[1] == "values" {
|
||||
itemID = parts[0]
|
||||
}
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), nil, itemID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, values)
|
||||
}
|
||||
|
||||
func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request struct {
|
||||
ItemValue
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ItemID == "" || request.FieldID == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||
`, request.ID, request.ItemID, request.FieldID, request.Value, int64(request.UpdatedAt))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||
return
|
||||
}
|
||||
var listID string
|
||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||
}
|
||||
var value ItemValue
|
||||
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
|
||||
&value.ID,
|
||||
&value.ItemID,
|
||||
&value.FieldID,
|
||||
&value.Value,
|
||||
&value.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, value)
|
||||
}
|
||||
|
||||
func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
id = strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/")
|
||||
}
|
||||
var request struct {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if r.Method == http.MethodPut || r.Method == http.MethodDelete {
|
||||
_ = decodeJSON(r, &request)
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
if r.Method == http.MethodPut {
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
return
|
||||
}
|
||||
item, err := s.getItem(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
return
|
||||
}
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
return
|
||||
}
|
||||
item, itemErr := s.getItem(r.Context(), id)
|
||||
if itemErr == nil {
|
||||
_, _ = s.db.pool.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, id)
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"message": "Item deleted successfully"})
|
||||
}
|
||||
|
||||
func (s *Server) handleItemPath(w http.ResponseWriter, r *http.Request) {
|
||||
suffix := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/")
|
||||
parts := strings.Split(suffix, "/")
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodGet && len(parts) == 2 && parts[0] == "list":
|
||||
s.handleItemsForList(w, r)
|
||||
case r.Method == http.MethodGet && len(parts) == 2 && parts[1] == "values":
|
||||
s.handleValuesForItem(w, r)
|
||||
case (r.Method == http.MethodPut || r.Method == http.MethodDelete) && len(parts) == 1 && parts[0] != "":
|
||||
s.handleItem(w, r)
|
||||
default:
|
||||
writeJSONError(w, http.StatusNotFound, "Not found")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user