README
ΒΆ
Models
Shared data models and TypeScript type definitions for the UUG AI ecosystem.
A comprehensive Go package providing type-safe data models for media management, device control, authentication, analytics, and more. Includes automatic TypeScript type generation for seamless cross-language development.
π Best Practices Guide - Comprehensive guidelines for defining Go types in this repository
Features
- Comprehensive Type System: 30+ models covering media, devices, authentication, analytics, and more
- Cross-Language Support: Automatic TypeScript type generation from Go structs
- Database Ready: Full MongoDB support with BSON tags and validation
- API Optimized: JSON serialization with proper omitempty handling
- Type Safety: Compile-time type checking in both Go and TypeScript
- Auto-Discovery: Automatic model detection and TypeScript generation
- Production Ready: Battle-tested models used in production systems
Installation
Go
go get github.com/uug-ai/models
TypeScript
npm install @uug-ai/models
# or
yarn add @uug-ai/models
Quick Start
Go Usage
package main
import (
"github.com/uug-ai/models/pkg/models"
"time"
)
func main() {
// Create a media record
media := models.Media{
FileName: "video_001.mp4",
StartTimestamp: time.Now().Unix(),
Duration: 600000, // 10 minutes in milliseconds
DeviceId: "camera-001",
UserId: "user-123",
VideoUrl: "https://cdn.example.com/videos/video_001.mp4",
ThumbnailUrl: "https://cdn.example.com/thumbs/video_001.jpg",
SpriteUrl: "https://cdn.example.com/sprites/video_001.jpg",
SpriteInterval: 10,
}
// Create a device
device := models.Device{
Name: "Front Door Camera",
DeviceId: "camera-001",
Type: "camera",
Status: "online",
GroupId: "group-001",
Coordinates: &models.Coordinates{
Latitude: 37.7749,
Longitude: -122.4194,
},
}
}
TypeScript Usage
import { Media, Device, models } from '@uug-ai/models';
// Direct import
const media: Media = {
fileName: "video_001.mp4",
startTimestamp: 1640995200,
duration: 600000,
deviceId: "camera-001",
userId: "user-123",
videoUrl: "https://cdn.example.com/videos/video_001.mp4"
};
// Namespace import
const device: models.Device = {
name: "Front Door Camera",
deviceId: "camera-001",
type: "camera",
status: "online"
};
Core Concepts
Pipeline transport compatibility
MonitorStage JSON serialization omits user.audit and the audit field of
every nested user.master. Pipeline workers do not use this audit history.
json.Unmarshal into PipelineEvent accepts and ignores absent, null, legacy
array, and current object audit values before queue handlers run; forwarding
and worker fanout through json.Marshal omit them for old and new readers.
All other user and pipeline fields retain their existing JSON representation.
Reusing a decode destination retains absent fields as usual; decoding a user
object clears its audit instead of retaining stale audit data.
This is a pipeline-only transport boundary: standalone User/Audit JSON
(including API responses) and all BSON persistence remain unchanged. No data
migration is required.
Automatic Type Generation
This project bridges Go and TypeScript using an automated pipeline:
- Go Models - Define structs in
pkg/models/with proper tags - Swagger Generation -
swagscans code and generates API spec - OpenAPI Conversion - Swagger 2.0 β OpenAPI 3.x format
- TypeScript Generation - OpenAPI spec β TypeScript types
- Post-Processing - Add convenient exports and build
This ensures type safety across your entire stack with a single source of truth.
Model Categories
The models package organizes types into logical categories:
- Media Models - Video, thumbnails, sprites, and media metadata
- Device Models - Cameras, sensors, and IoT device management
- Authentication - Users, tokens, permissions, and access control
- Analytics - Metrics, timelines, and data analysis
- Integration - Third-party service connections and webhooks
- Infrastructure - Health checks, configurations, and system status
Usage Examples
Generating TypeScript Types
The primary workflow for maintaining cross-language type safety:
# Generate both OpenAPI spec and TypeScript types
npm run generate
# Or run steps individually:
npm run generate:openapi # Go models β OpenAPI 3.x YAML
npm run generate:types # OpenAPI YAML β TypeScript types
Generated Files:
docs/swagger.yaml- Swagger 2.0 specification (intermediate)docs/openapi.yaml- OpenAPI 3.x specificationsrc/typescript/types.ts- TypeScript type definitions
Adding New Models
- Create Go struct in
pkg/models/:
package models
// User represents a system user
type User struct {
ID string `json:"id" bson:"_id,omitempty"`
Email string `json:"email" bson:"email" validate:"required,email"`
Name string `json:"name" bson:"name" validate:"required"`
CreatedAt int64 `json:"createdAt" bson:"createdAt"`
}
- Reference in
cmd/main.go:
// Just declare a variable or add to API endpoint
var _ = models.User{}
- Generate TypeScript types:
npm run generate
No manual script updates needed! The generation pipeline automatically discovers all referenced models.
Media Management Example
package main
import (
"context"
"time"
"github.com/uug-ai/models/pkg/models"
"go.mongodb.org/mongo-driver/mongo"
)
func saveMedia(collection *mongo.Collection, deviceId string) error {
media := models.Media{
FileName: "recording_2024.mp4",
StartTimestamp: time.Now().Add(-1 * time.Hour).Unix(),
EndTimestamp: time.Now().Unix(),
Duration: 3600000, // 1 hour in milliseconds
Provider: "aws-s3",
Storage: "media-bucket",
DeviceId: deviceId,
VideoUrl: "https://cdn.example.com/videos/recording_2024.mp4",
ThumbnailUrl: "https://cdn.example.com/thumbs/recording_2024.jpg",
ThumbnailFile: "recording_2024_thumb.jpg",
SpriteUrl: "https://cdn.example.com/sprites/recording_2024.jpg",
SpriteFile: "recording_2024_sprite.jpg",
SpriteInterval: 10,
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := collection.InsertOne(ctx, media)
return err
}
Device Registration Example
package main
import (
"github.com/uug-ai/models/pkg/models"
"time"
)
func registerDevice(name, deviceId string, lat, lng float64) models.Device {
return models.Device{
Name: name,
DeviceId: deviceId,
Type: "camera",
Status: "online",
GroupId: "group-001",
CreatedAt: time.Now().Unix(),
UpdatedAt: time.Now().Unix(),
Coordinates: &models.Coordinates{
Latitude: lat,
Longitude: lng,
},
Capabilities: []string{"video", "audio", "motion-detection"},
}
}
API Response Handling
package main
import (
"encoding/json"
"net/http"
"github.com/uug-ai/models/pkg/api"
)
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
response := api.HealthResponse{
Status: "healthy",
Timestamp: time.Now().Unix(),
Version: "1.0.0",
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func errorHandler(w http.ResponseWriter, message string, code int) {
response := api.ErrorResponse{
Error: true,
Message: message,
StatusCode: code,
Timestamp: time.Now().Unix(),
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(response)
}
Project Structure
.
βββ pkg/
β βββ models/ # Core data models
β β βββ media.go # Media and video models
β β βββ device.go # Device management models
β β βββ user.go # User and authentication models
β β βββ authentication.go # Auth tokens and sessions
β β βββ analysis.go # Analytics and metrics
β β βββ pipeline.go # Processing pipelines
β β βββ integration.go # Third-party integrations
β β βββ ... # 30+ additional models
β βββ api/ # API response structures
β βββ api.go # Common API types
β βββ media.go # Media API responses
β βββ device.go # Device API responses
β βββ ...
βββ cmd/
β βββ main.go # Model auto-discovery entry point
βββ scripts/
β βββ auto-discover-models.js # Automatic model detection
β βββ add-type-exports.js # TypeScript export generation
βββ src/
β βββ typescript/
β βββ types.ts # Generated TypeScript types
β βββ package.json
βββ docs/
β βββ swagger.yaml # Swagger 2.0 spec
β βββ openapi.yaml # OpenAPI 3.x spec
βββ go.mod
βββ package.json
βββ BEST_PRACTICES.md # Type definition guidelines
βββ README.md
Configuration
Development Setup
- Clone the repository:
git clone https://github.com/uug-ai/models.git
cd models
- Install Go dependencies:
go mod download
- Install Node.js dependencies:
npm install
- Install Swagger CLI:
go install github.com/swaggo/swag/cmd/swag@latest
Environment Variables
TypeScript generation can be configured via environment:
# Skip OpenAPI generation (use existing spec)
SKIP_OPENAPI=true npm run generate
# Verbose output
DEBUG=true npm run generate
Available Models
Core Models (pkg/models/)
Media- Video files, thumbnails, sprites, and metadataDevice- Cameras, sensors, and IoT devicesUser- User accounts and profilesAuthentication- Auth tokens, sessions, and credentialsAccessToken- API access tokens and permissionsGroup- User groups and organizationsSite- Physical locations and sitesAnalysis- Analytics data and metricsPipeline- Data processing pipelinesStrategy- Processing strategies and configurationsMarker- Timeline markers and annotationsActivity- User activity logsAlert- System alerts and notificationsAudit- Audit logs and complianceComment- User comments and feedbackConfig- System configurationsFloorPlan- Site floor plans and layoutsHealth- Health check dataIntegration- Third-party integrationsLocation- Geographic locationsMessage- System messages and notificationsObject- Object detection resultsPermission- Access permissionsProvider- Service providersRole- User roles and capabilitiesSubscription- Subscription and billingVault- Secure credential storage
API Models (pkg/api/)
ErrorResponse- Standard error responses
Selective Fields
Clients can request optional fields on certain API payloads using the include parameter in request models. For example, site option queries support include: ["metadata"] to return site metadata alongside the default fields.
HealthResponse- Health check responsesPaginationResponse- Paginated list responsesMediaResponse- Media query responsesDeviceResponse- Device query responsesAnalysisResponse- Analytics responses
Validation
Models use go-playground/validator for field validation:
type User struct {
Email string `json:"email" validate:"required,email"`
Name string `json:"name" validate:"required,min=2,max=100"`
Age int `json:"age" validate:"gte=0,lte=150"`
Role string `json:"role" validate:"required,oneof=admin user guest"`
}
// Validate in your code
import "github.com/go-playground/validator/v10"
validate := validator.New()
err := validate.Struct(user)
if err != nil {
// Handle validation errors
}
Common validation tags:
required- Field must be presentemail- Valid email formatmin=n- Minimum length/valuemax=n- Maximum length/valueoneof=a b c- Must be one of specified valuesgte=n,lte=n- Range validation
Testing
Run the test suite:
go test ./...
Run tests with coverage:
go test -cover ./...
Run tests for specific packages:
# Model tests
go test ./pkg/models -v
# Pipeline tests
go test ./pkg/models -run TestPipeline
Contributing
Contributions are welcome! Please follow the guidelines in BEST_PRACTICES.md when adding new models.
Development Guidelines
- Fork the repository
- Create a feature branch (
git checkout -b feat/amazing-model) - Add your model to
pkg/models/orpkg/api/ - Include proper JSON, BSON, and validation tags
- Reference the model in
cmd/main.go - Generate TypeScript types:
npm run generate - Add tests for your model
- Ensure all tests pass:
go test ./... - Commit following Conventional Commits
- Push to your branch (
git push origin feat/amazing-model) - Open a Pull Request
Commit Message Format
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, types
Scopes:
models- Changes to Go model structs inpkg/models/api- Changes to API response structures inpkg/api/types- TypeScript type generation or definitionsscripts- Build/generation scriptsdocs- Documentation updates
Examples:
feat(models): add sprite interval field to Media struct
fix(api): correct JSON tags for ErrorResponse message field
docs(readme): update TypeScript generation workflow
refactor(models): standardize BSON tag formatting across all structs
types: regenerate TypeScript definitions from updated Go models
License
This project is licensed under the MIT License - see the LICENSE file for details.
Dependencies
This project uses the following key libraries:
- swaggo/swag - Swagger/OpenAPI generation from Go
- mongo-driver - Official MongoDB Go driver
- go-playground/validator - Struct validation
- openapi-typescript - TypeScript generation from OpenAPI
- swagger2openapi - Swagger to OpenAPI conversion
See go.mod and package.json for complete dependency lists.
Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: See BEST_PRACTICES.md and inline code comments
Documentation
ΒΆ
There is no documentation for this package.
Directories
ΒΆ
| Path | Synopsis |
|---|---|
|
pkg
|
|
|
scripts
|
|
|
generate-properties
command
generate-properties parses Go model files and generates property constants based on the bson tags found in struct fields.
|
generate-properties parses Go model files and generates property constants based on the bson tags found in struct fields. |