Clay is a globally installed command-line tool. Install it using npm:
npm install -g clay-generator
Verify the installation by running:
clay --version
Navigate to your project directory and initialize Clay:
cd my-project
clay init
This creates a .clay file that tracks all generated
files.
Create a directory for your Clay configuration and model:
mkdir -p clay
cat > clay/model.json << 'EOF'
{
"name": "user-service",
"generators": ["./generators/api"],
"model": {
"types": [
{
"name": "User",
"fields": [
{ "name": "id", "type": "string" },
{ "name": "email", "type": "string" },
{ "name": "name", "type": "string" }
]
}
]
}
}
EOF
Create a simple generator that creates a model file:
mkdir -p clay/generators/api/templates
cat > clay/generators/api/generator.json << 'EOF'
{
"partials": [],
"steps": [
{
"generate": "templates/model.js",
"select": "$.model.types[*]",
"target": "src/models/{{kebabCase name}}.model.js"
}
],
"formatters": []
}
EOF
Create a Handlebars template for the generated files:
cat > clay/generators/api/templates/model.js << 'EOF'
// Generated Model: {{name}}
class {{pascalCase name}} {
constructor(data) {
{{#each fields}}
this.{{name}} = data.{{name}};
{{/each}}
}
toJSON() {
return {
{{#each fields}}
{{name}}: this.{{name}},
{{/each}}
};
}
}
module.exports = {{pascalCase name}};
EOF
Now generate your code:
clay generate clay/model.json ./
Or, since you have a .clay file, you can simply run:
clay generate
This creates src/models/user.model.js based on your
model!
A typical Clay project looks like this:
.
├── .clay # Tracks generated files
├── clay/ # Clay configuration
│ ├── model.json # Your domain model
│ └── generators/ # Custom generators
│ └── api/
│ ├── generator.json
│ └── templates/
│ └── model.js
└── src/ # Generated code appears here
└── models/
└── user.model.js
Generate code from your model:
clay generate <model_path> <output_path>
clay generate # Uses .clay file
Remove all generated files:
clay clean <model_path> <output_path>
clay clean # Uses .clay file
Automatically regenerate when files change:
clay watch <model_path> <output_path>
clay watch # Uses .clay file
Test JSONPath expressions against your model:
clay test-path <model_path> "$.model.types[*].fields[*]"
watch command during
development to automatically regenerate code as you modify your model
or templates!