I'm trying to convert my object modeling tool, built with TypeScript, to Go.
What I have in TypeScript is:
interface SchemaType {
[key: string]: {
type: string;
required?: boolean;
default?: any;
validate?: any[];
maxlength?: any[];
minlength?: any[],
transform?: Function;
};
};
class Schema {
private readonly schema;
constructor(schema: SchemaType) {
this.schema = schema;
};
public validate(data: object): Promise<object> {
// Do something with data
return data;
};
};
So that I can then do:
const itemSchema = new Schema({
id: {
type: String,
required: true
},
createdBy: {
type: String,
required: true
}
});
I've only gotten this far with Go:
type SchemaType struct {
Key string // I'm not sure about this bit
Type string
Required bool
Default func()
Validate [2]interface{}
Maxlength [2]interface{}
Minlength [2]interface{}
Transform func()
}
type Schema struct {
schema SchemaType
}
func (s *Schema) NewSchema(schema SchemaType) {
s.schema = schema
}
func (s *Schema) Validate(collection string, data map[string]interface{}) map[string]interface{} {
// do something with data
return data
}
I'm a little stuck mainly because of the dynamic "key" in the SchemaType interface and am not sure how to replicate this in Go...
CodePudding user response:
The [key string]:
part means that it's a dictionary with keys of type string
. In Go that would be a map[string]<some type>
.
type SchemaType map[string]SchemaTypeEntry
type SchemaTypeEntry struct {
Type string
Required bool
// ...
}
or, drop the SchemaType
type and change Schema
:
type Schema struct {
schema map[string]SchemaTypeEntry
}
Now, about the other fields, the look odd as you have defined them, and it's likely that it will not work the way you are showing here.
Default
would be a value, not a func()
(a function that doesn't return anything). You don't know what type the value is, so the type should be interface {}
or any
(since Go 1.18 - an alias for interface {}
).
Transform
- that would likely be a function that takes a value, transforms it, and returns a value - func(interface{}) interface{}
No idea what MinLength
, MaxLength
and Validate
stand for in this context - it is unclear why they are arrays in Javascript, and how you can be sure that they are of exactly length 2 in Go.