2018-09-22 12:34:26 +02:00
|
|
|
import { Type } from "./Type"
|
|
|
|
|
|
|
|
export class ObjectType implements Type {
|
2019-03-26 06:34:40 +01:00
|
|
|
public kind = "object"
|
2018-09-22 12:34:26 +02:00
|
|
|
|
2018-11-04 17:20:01 +01:00
|
|
|
// Note: a map that has an empty key ("") uses the corresponding type as default type
|
2019-05-31 13:25:51 +02:00
|
|
|
constructor(public members: Map<string, Type> = new Map<string, Type>(), public isDotDotDot = false, public isQuestion = false) {}
|
2018-09-22 12:34:26 +02:00
|
|
|
|
2019-03-26 06:34:40 +01:00
|
|
|
public toConstructor() {
|
2018-11-04 17:20:01 +01:00
|
|
|
return `new ObjectType(new Map<string, Type>([` +
|
|
|
|
Array.from(this.members.entries()).map(([n, m]) => `[${JSON.stringify(n)}, ${m.toConstructor()}]`)
|
|
|
|
.join(", ") +
|
2019-05-31 13:25:51 +02:00
|
|
|
`]), ${this.isDotDotDot}, ${this.isQuestion})`
|
2018-09-22 12:34:26 +02:00
|
|
|
}
|
|
|
|
|
2019-03-26 06:34:40 +01:00
|
|
|
public toString() {
|
2018-09-22 12:34:26 +02:00
|
|
|
return this.kind
|
|
|
|
}
|
|
|
|
|
2019-03-26 06:34:40 +01:00
|
|
|
public convertMember(memberName: string[], memberValue: string) {
|
2018-11-04 17:20:01 +01:00
|
|
|
let type = this.members.get(memberName[0])
|
|
|
|
if (!type) {
|
|
|
|
// No type, try to get the default type
|
|
|
|
type = this.members.get("")
|
|
|
|
if (!type) {
|
|
|
|
// No info for this member and no default type, anything goes
|
|
|
|
return memberValue
|
|
|
|
}
|
|
|
|
}
|
2019-03-26 06:34:40 +01:00
|
|
|
if (type.kind === "object") {
|
2018-11-04 17:20:01 +01:00
|
|
|
return (type as ObjectType).convertMember(memberName.slice(1), memberValue)
|
|
|
|
}
|
|
|
|
return type.convert(memberValue)
|
|
|
|
}
|
|
|
|
|
2019-03-26 06:34:40 +01:00
|
|
|
public convert(argument) {
|
2018-09-22 12:34:26 +02:00
|
|
|
try {
|
|
|
|
return JSON.parse(argument)
|
|
|
|
} catch (e) {
|
|
|
|
throw new Error(`Can't convert to object: ${argument}`)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|