63 lines
1.4 KiB
Plaintext
63 lines
1.4 KiB
Plaintext
// Example: How to add builtins to the framework
|
|
// Just write a Go function and register it - that's all!
|
|
|
|
package standard
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/dop251/goja"
|
|
"reichard.io/poiesis/internal/runtime/pkg/builtin"
|
|
)
|
|
|
|
// Simple function - just register it!
|
|
func multiply(a, b int) int {
|
|
return a * b
|
|
}
|
|
|
|
// Function returning multiple values with error
|
|
func divide(a, b int) (int, error) {
|
|
if b == 0 {
|
|
return 0, fmt.Errorf("cannot divide by zero")
|
|
}
|
|
return a / b, nil
|
|
}
|
|
|
|
// Complex example with struct
|
|
type User struct {
|
|
Name string
|
|
Email string
|
|
Age int
|
|
}
|
|
|
|
func getUser(id int) (User, error) {
|
|
return User{
|
|
Name: "John Doe",
|
|
Email: "john@example.com",
|
|
Age: 30,
|
|
}, nil
|
|
}
|
|
|
|
// Optional: Register custom converter for User type
|
|
func convertUser(vm *goja.Runtime, user User) goja.Value {
|
|
obj := vm.NewObject()
|
|
_ = obj.Set("name", user.Name)
|
|
_ = obj.Set("email", user.Email)
|
|
_ = obj.Set("age", user.Age)
|
|
return obj
|
|
}
|
|
|
|
// In a real file, you'd put this in init():
|
|
//
|
|
// func init() {
|
|
// builtin.RegisterCustomConverter(convertUser)
|
|
// builtin.RegisterBuiltin("multiply", multiply)
|
|
// builtin.RegisterBuiltin("divide", divide)
|
|
// builtin.RegisterBuiltin("getUser", getUser)
|
|
// }
|
|
|
|
// That's it! TypeScript definitions are auto-generated:
|
|
// declare function multiply(arg0: number, arg1: number): number;
|
|
// declare function divide(arg0: number, arg1: number): number;
|
|
// declare function getUser(arg0: number): User;
|