v2 / vlib / v / tests / options / option_arr_auto_str_test.v
68 lines · 63 sloc · 1.49 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1import x.json2
2
3pub fn maybe_map[T, X](a []T, f fn (T) !X) ![]X {
4 mut r := []X{cap: a.len}
5 for v in a {
6 r << f(v)!
7 }
8 return r
9}
10
11pub enum ApplicationCommandOptionType {
12 sub_command = 1
13 sub_command_group
14 string
15 integer
16 boolean
17 user
18 channel
19 role
20 mentionable
21 number
22 attachment
23}
24
25pub struct ApplicationCommandOption {
26pub:
27 typ ApplicationCommandOptionType @[required]
28 name string @[required]
29 description string @[required]
30 options ?[]ApplicationCommandOption
31}
32
33pub fn ApplicationCommandOption.parse(j json2.Any) !ApplicationCommandOption {
34 match j {
35 map[string]json2.Any {
36 return ApplicationCommandOption{
37 typ: unsafe { ApplicationCommandOptionType(j['type']!.int()) }
38 name: j['name']! as string
39 description: j['description']! as string
40 options: if a := j['options'] {
41 maybe_map(a as []json2.Any, fn (k json2.Any) !ApplicationCommandOption {
42 return ApplicationCommandOption.parse(k)!
43 })!
44 } else {
45 none
46 }
47 }
48 }
49 else {
50 return error('expected application command option to be object, got ${j.type_name()}')
51 }
52 }
53}
54
55fn test_main() {
56 assert ApplicationCommandOption.parse({
57 'type': json2.Any(3)
58 'name': 'foo'
59 'description': 'This is my first command.'
60 }) or {
61 assert false, 'Should not return error: ${err}'
62 return
63 } == ApplicationCommandOption{
64 typ: .string
65 name: 'foo'
66 description: 'This is my first command.'
67 }
68}
69