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
- 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
go get github.com/uug-ai/modelsnpm install @uug-ai/models
# or
yarn add @uug-ai/modelspackage 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,
},
}
}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"
};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.
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
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 typesGenerated Files:
docs/swagger.yaml- Swagger 2.0 specification (intermediate)docs/openapi.yaml- OpenAPI 3.x specificationsrc/typescript/types.ts- TypeScript type definitions
- 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:"created_at"`
}- Reference in
cmd/main.go:
// Just declare a variable or add to API endpoint
var _ = models.User{}- Generate TypeScript types:
npm run generateNo manual script updates needed! The generation pipeline automatically discovers all referenced models.
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
}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"},
}
}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)
}.
├── 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
- 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@latestTypeScript generation can be configured via environment:
# Skip OpenAPI generation (use existing spec)
SKIP_OPENAPI=true npm run generate
# Verbose output
DEBUG=true npm run generateMedia- 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
ErrorResponse- Standard error responsesHealthResponse- Health check responsesPaginationResponse- Paginated list responsesMediaResponse- Media query responsesDeviceResponse- Device query responsesAnalysisResponse- Analytics responses
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
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 TestPipelineContributions are welcome! Please follow the guidelines in BEST_PRACTICES.md when adding new models.
- 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
<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
This project is licensed under the MIT License - see the LICENSE file for details.
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.
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: See BEST_PRACTICES.md and inline code comments