Skip to content

Commit bbb8e70

Browse files
Shared library templates
1 parent ec40917 commit bbb8e70

File tree

8 files changed

+419
-0
lines changed

8 files changed

+419
-0
lines changed

templates/libs/go/README.md

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# {{name}}
2+
3+
A shared Go module generated by create-polyglot for cross-service utilities and models.
4+
5+
## Installation
6+
7+
### Add to Go Module
8+
9+
```bash
10+
# From your service directory
11+
go mod edit -require={{name}}@v0.1.0
12+
go mod edit -replace={{name}}=../packages/{{name}}
13+
```
14+
15+
### Usage in Services
16+
17+
```go
18+
package main
19+
20+
import (
21+
"fmt"
22+
"{{name}}"
23+
)
24+
25+
func main() {
26+
// Use shared utilities
27+
response := {{name}}.FormatResponse(map[string]string{"key": "value"}, "success", nil)
28+
29+
// Use shared models
30+
health := {{name}}.NewServiceHealth("api", "healthy")
31+
32+
// Use utility functions
33+
config := map[string]interface{}{
34+
"database_url": "localhost:5432",
35+
"api_key": "secret",
36+
}
37+
isValid := {{name}}.ValidateConfig(config, []string{"database_url", "api_key"})
38+
newID := {{name}}.GenerateID()
39+
40+
fmt.Printf("Response: %+v\n", response)
41+
fmt.Printf("Health: %s\n", health)
42+
fmt.Printf("Config Valid: %v\n", isValid)
43+
fmt.Printf("Generated ID: %s\n", newID)
44+
}
45+
```
46+
47+
## Development
48+
49+
### Install Dependencies
50+
51+
```bash
52+
go mod tidy
53+
```
54+
55+
### Running Tests
56+
57+
```bash
58+
go test ./...
59+
```
60+
61+
### Build
62+
63+
```bash
64+
go build
65+
```
66+
67+
## Structure
68+
69+
- `go.mod` - Go module definition
70+
- `{{name}}.go` - Main package with shared utilities and models
71+
- `README.md` - This file
72+
73+
## Adding to Services
74+
75+
To use this shared module in your Go services:
76+
77+
1. Add the module dependency:
78+
```bash
79+
go mod edit -require={{name}}@v0.1.0
80+
go mod edit -replace={{name}}=../packages/{{name}}
81+
```
82+
83+
2. Import and use in your service code:
84+
```go
85+
import "{{name}}"
86+
```
87+
88+
## Types and Functions
89+
90+
### Types
91+
92+
- `Response` - Standardized API response structure
93+
- `ServiceHealth` - Service health status model
94+
- `ErrorResponse` - Standardized error response structure
95+
96+
### Functions
97+
98+
- `FormatResponse(data, status, message)` - Create standardized API response
99+
- `ValidateConfig(config, requiredKeys)` - Validate configuration keys
100+
- `SafeJSONUnmarshal(data, v, defaultValue)` - Safe JSON unmarshaling with fallback
101+
- `GenerateID()` - Generate new UUID string
102+
- `NewServiceHealth(serviceName, status)` - Create new ServiceHealth instance
103+
- `NewErrorResponse(code, message, details)` - Create new ErrorResponse instance

templates/libs/go/go.mod

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module {{name}}
2+
3+
go 1.21
4+
5+
require (
6+
github.com/google/uuid v1.4.0
7+
)

templates/libs/go/{{name}}.go

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// Package {{name}} provides shared utilities and models for create-polyglot monorepo
2+
package {{name}}
3+
4+
import (
5+
"encoding/json"
6+
"fmt"
7+
"time"
8+
9+
"github.com/google/uuid"
10+
)
11+
12+
// Response represents a standardized API response
13+
type Response struct {
14+
Status string `json:"status"`
15+
Timestamp string `json:"timestamp"`
16+
Data interface{} `json:"data"`
17+
Message *string `json:"message,omitempty"`
18+
}
19+
20+
// ServiceHealth represents the health status of a service
21+
type ServiceHealth struct {
22+
ID string `json:"id"`
23+
ServiceName string `json:"service_name"`
24+
Status string `json:"status"` // "healthy", "degraded", "unhealthy"
25+
Version *string `json:"version,omitempty"`
26+
Uptime *float64 `json:"uptime,omitempty"`
27+
LastCheck *time.Time `json:"last_check,omitempty"`
28+
CreatedAt time.Time `json:"created_at"`
29+
UpdatedAt time.Time `json:"updated_at"`
30+
}
31+
32+
// ErrorResponse represents a standardized error response
33+
type ErrorResponse struct {
34+
ID string `json:"id"`
35+
ErrorCode string `json:"error_code"`
36+
ErrorMessage string `json:"error_message"`
37+
Details map[string]interface{} `json:"details,omitempty"`
38+
CreatedAt time.Time `json:"created_at"`
39+
UpdatedAt time.Time `json:"updated_at"`
40+
}
41+
42+
// FormatResponse creates a standardized API response
43+
func FormatResponse(data interface{}, status string, message *string) Response {
44+
return Response{
45+
Status: status,
46+
Timestamp: time.Now().UTC().Format(time.RFC3339),
47+
Data: data,
48+
Message: message,
49+
}
50+
}
51+
52+
// ValidateConfig checks that all required keys exist in the configuration map
53+
func ValidateConfig(config map[string]interface{}, requiredKeys []string) bool {
54+
for _, key := range requiredKeys {
55+
if _, exists := config[key]; !exists {
56+
return false
57+
}
58+
}
59+
return true
60+
}
61+
62+
// SafeJSONUnmarshal safely unmarshals JSON with fallback to default value
63+
func SafeJSONUnmarshal(data []byte, v interface{}, defaultValue interface{}) interface{} {
64+
if err := json.Unmarshal(data, v); err != nil {
65+
return defaultValue
66+
}
67+
return v
68+
}
69+
70+
// GenerateID generates a new UUID string
71+
func GenerateID() string {
72+
return uuid.New().String()
73+
}
74+
75+
// NewServiceHealth creates a new ServiceHealth instance
76+
func NewServiceHealth(serviceName, status string) ServiceHealth {
77+
now := time.Now().UTC()
78+
return ServiceHealth{
79+
ID: GenerateID(),
80+
ServiceName: serviceName,
81+
Status: status,
82+
CreatedAt: now,
83+
UpdatedAt: now,
84+
}
85+
}
86+
87+
// NewErrorResponse creates a new ErrorResponse instance
88+
func NewErrorResponse(errorCode, errorMessage string, details map[string]interface{}) ErrorResponse {
89+
now := time.Now().UTC()
90+
return ErrorResponse{
91+
ID: GenerateID(),
92+
ErrorCode: errorCode,
93+
ErrorMessage: errorMessage,
94+
Details: details,
95+
CreatedAt: now,
96+
UpdatedAt: now,
97+
}
98+
}
99+
100+
// String returns a string representation of the ServiceHealth
101+
func (sh ServiceHealth) String() string {
102+
return fmt.Sprintf("ServiceHealth{ID: %s, Service: %s, Status: %s}", sh.ID, sh.ServiceName, sh.Status)
103+
}

templates/libs/python/README.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# {{name}}
2+
3+
A shared Python library generated by create-polyglot for cross-service utilities and models.
4+
5+
## Installation
6+
7+
### Development Install
8+
9+
```bash
10+
# From the monorepo root
11+
pip install -e packages/{{name}}
12+
```
13+
14+
### Usage in Services
15+
16+
```python
17+
from {{name}} import format_response, ServiceHealth
18+
from {{name}}.utils import validate_config, generate_id
19+
20+
# Use shared utilities
21+
response = format_response({"key": "value"}, "success", "Operation completed")
22+
23+
# Use shared models
24+
health = ServiceHealth(service_name="api", status="healthy", version="1.0.0")
25+
26+
# Use utility functions
27+
config_valid = validate_config(config_dict, ["database_url", "api_key"])
28+
new_id = generate_id()
29+
```
30+
31+
## Development
32+
33+
### Install Development Dependencies
34+
35+
```bash
36+
pip install -e ".[dev]"
37+
```
38+
39+
### Running Tests
40+
41+
```bash
42+
pytest
43+
```
44+
45+
### Code Formatting
46+
47+
```bash
48+
black .
49+
flake8 .
50+
mypy .
51+
```
52+
53+
## Structure
54+
55+
- `{{name}}/` - Main package directory
56+
- `__init__.py` - Package initialization and exports
57+
- `utils.py` - Shared utility functions
58+
- `models.py` - Shared data models and classes
59+
- `pyproject.toml` - Package configuration
60+
- `README.md` - This file
61+
62+
## Adding to Services
63+
64+
To use this shared library in your Python services:
65+
66+
1. Add the dependency to your service's `requirements.txt`:
67+
```
68+
-e ../packages/{{name}}
69+
```
70+
71+
2. Import and use in your service code:
72+
```python
73+
from {{name}} import format_response
74+
```

templates/libs/python/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
"""
2+
{{name}} - A shared Python library for create-polyglot monorepo
3+
"""
4+
5+
__version__ = "0.1.0"
6+
7+
from .utils import *
8+
from .models import *

templates/libs/python/models.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Shared data models for {{name}}
3+
"""
4+
5+
from typing import Optional
6+
from dataclasses import dataclass
7+
import datetime
8+
9+
10+
@dataclass
11+
class BaseModel:
12+
"""Base model with common fields."""
13+
id: Optional[str] = None
14+
created_at: Optional[datetime.datetime] = None
15+
updated_at: Optional[datetime.datetime] = None
16+
17+
def __post_init__(self):
18+
if self.created_at is None:
19+
self.created_at = datetime.datetime.utcnow()
20+
if self.updated_at is None:
21+
self.updated_at = datetime.datetime.utcnow()
22+
23+
24+
@dataclass
25+
class ServiceHealth(BaseModel):
26+
"""Model for service health status."""
27+
service_name: str
28+
status: str # "healthy", "degraded", "unhealthy"
29+
version: Optional[str] = None
30+
uptime: Optional[float] = None
31+
last_check: Optional[datetime.datetime] = None
32+
33+
34+
@dataclass
35+
class ErrorResponse(BaseModel):
36+
"""Model for standardized error responses."""
37+
error_code: str
38+
error_message: str
39+
details: Optional[dict] = None
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
[build-system]
2+
requires = ["setuptools>=45", "wheel"]
3+
build-backend = "setuptools.build_meta"
4+
5+
[project]
6+
name = "{{name}}"
7+
version = "0.1.0"
8+
description = "A shared Python library for create-polyglot monorepo"
9+
readme = "README.md"
10+
requires-python = ">=3.8"
11+
authors = [
12+
{name = "Generated by create-polyglot"}
13+
]
14+
classifiers = [
15+
"Development Status :: 4 - Beta",
16+
"Intended Audience :: Developers",
17+
"License :: OSI Approved :: MIT License",
18+
"Programming Language :: Python :: 3",
19+
"Programming Language :: Python :: 3.8",
20+
"Programming Language :: Python :: 3.9",
21+
"Programming Language :: Python :: 3.10",
22+
"Programming Language :: Python :: 3.11",
23+
]
24+
dependencies = [
25+
"typing-extensions>=4.0.0"
26+
]
27+
28+
[project.optional-dependencies]
29+
dev = [
30+
"pytest>=7.0.0",
31+
"black>=22.0.0",
32+
"flake8>=4.0.0",
33+
"mypy>=0.950"
34+
]
35+
36+
[tool.setuptools.packages.find]
37+
where = ["."]
38+
include = ["{{name}}*"]
39+
40+
[tool.black]
41+
line-length = 88
42+
target-version = ["py38"]
43+
44+
[tool.mypy]
45+
python_version = "3.8"
46+
warn_return_any = true
47+
warn_unused_configs = true
48+
disallow_untyped_defs = true

0 commit comments

Comments
 (0)