Search code examples
schemacuelang

Is it possible to extend definition in CueLang


Is it possible to extend Definition?

For example, lets say that we want to have Connection definition like this

Connection :: {
    protocol: "tcp" | "udp"
    port: int
    host: string
}

And we also want to have SecureConnection that has everything that Connection has, but we also like to add username and password. How to achieve this?

I can do it like this

Connection :: {
    protocol: "tcp" | "udp"
    port: int
    host: string
    ...
}

SecureConnection :: Connection & {
    username: string & >""
    password: string & >""
}

and it will work, but this also means, that this is not closed. Because of that three dots in Connection definition, we can add anything we want to secure connection

for example

tcp: SecureConnection & {
    protocol: "tcp"
    port: 8080
    host: "localhost"
    username: "guest"
    password: "guest"
    test: "testing"
    oneUnimportantVariable: "I am not important"
}

when I run cue export myfile.cue this will give me following JSON

{
    "tcp": {
        "protocol": "tcp",
        "port": 8080,
        "host": "localhost",
        "username": "guest",
        "password": "guest",
        "test": "testing",
        "oneUnimportantVariable": "I am not important"
    }
}

So, how to extend Connection definition and create SecureConnection definition, and not be able to specify any variable that isn't specify in this definition?


Solution

  • You can use definition embedding as below

    Connection :: {
        protocol: "tcp" | "udp"
        port: int
        host: string
    }
    
    SecureConnection :: {
        Connection
        username: string & >""
        password: string & >""
    }