2022-05-19 07:54:33 +02:00
|
|
|
module models
|
|
|
|
|
2022-05-29 20:08:21 +02:00
|
|
|
import time
|
|
|
|
|
2022-05-19 22:14:41 +02:00
|
|
|
// from_params<T> creates a new instance of T from the given map by parsing all
|
|
|
|
// of its fields from the map.
|
2022-05-19 07:54:33 +02:00
|
|
|
pub fn from_params<T>(params map[string]string) ?T {
|
|
|
|
mut o := T{}
|
|
|
|
|
|
|
|
patch_from_params<T>(mut o, params)?
|
|
|
|
|
|
|
|
return o
|
|
|
|
}
|
|
|
|
|
2022-05-19 22:14:41 +02:00
|
|
|
// patch_from_params<T> updates the given T object with the params defined in
|
|
|
|
// the map.
|
2022-05-19 07:54:33 +02:00
|
|
|
pub fn patch_from_params<T>(mut o T, params map[string]string) ? {
|
|
|
|
$for field in T.fields {
|
|
|
|
if field.name in params && params[field.name] != '' {
|
|
|
|
$if field.typ is string {
|
|
|
|
o.$(field.name) = params[field.name]
|
|
|
|
} $else $if field.typ is int {
|
|
|
|
o.$(field.name) = params[field.name].int()
|
|
|
|
} $else $if field.typ is u64 {
|
|
|
|
o.$(field.name) = params[field.name].u64()
|
2022-06-14 22:25:40 +02:00
|
|
|
} $else $if field.typ is []TargetArch {
|
|
|
|
o.$(field.name) = params[field.name].split(',').map(TargetArch{ value: it })
|
2022-05-29 20:08:21 +02:00
|
|
|
} $else $if field.typ is time.Time {
|
|
|
|
o.$(field.name) = time.unix(params[field.name].int())
|
|
|
|
} $else $if field.typ is []string {
|
|
|
|
o.$(field.name) = params[field.name].split(',')
|
2022-05-19 07:54:33 +02:00
|
|
|
}
|
|
|
|
} else if field.attrs.contains('nonull') {
|
|
|
|
return error('Missing parameter: ${field.name}.')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-19 22:14:41 +02:00
|
|
|
// params_from<T> converts a given T struct into a map of strings.
|
2022-05-19 07:54:33 +02:00
|
|
|
pub fn params_from<T>(o &T) map[string]string {
|
|
|
|
mut out := map[string]string{}
|
|
|
|
|
|
|
|
$for field in T.fields {
|
2022-05-29 21:07:46 +02:00
|
|
|
$if field.typ is time.Time {
|
|
|
|
out[field.name] = o.$(field.name).unix_time().str()
|
|
|
|
} $else $if field.typ is []string {
|
|
|
|
out[field.name] = o.$(field.name).join(',')
|
|
|
|
} $else {
|
|
|
|
out[field.name] = o.$(field.name).str()
|
|
|
|
}
|
2022-05-19 07:54:33 +02:00
|
|
|
}
|
|
|
|
return out
|
|
|
|
}
|