#making JSONValue.field nullable

1 messages · Page 1 of 1 (latest)

native chasm
#

e.g. this:

  """
  Optional source include paths from package.json "docusaurus.include".
  """
  pub include: [String!]! {
    if (json == null) {
      [] :: [String!]!
    } else if (hasField(json, "docusaurus") == false) {
      [] :: [String!]!
    } else {
      let docusaurus = json.field(["docusaurus"])
      if (hasField(docusaurus, "include") == false) {
        [] :: [String!]!
      } else {
        let include = docusaurus.field(["include"])
        include.asArray.{asString}.map { item => item.asString }
      }
    }
  }

becomes just:

  """
  Optional source include paths from package.json "docusaurus.include".
  """
  pub include: [String!]! {
    json.field(["docusaurus", "include"]).asArray.{asString}.map { item => item.asString } ?? []
  }
#

here too:

  """
  The package manager command (read from package.json "packageManager" field).
  """
  pub packageManager: String! {
    if (json == null) {
      "npm"
    } else if (hasField(json, "packageManager") == false) {
      "npm"
    } else {
      let pmField = json.field(["packageManager"])
      # packageManager field is like "pnpm@8.15.0" — take the name before @
      pmField.asString.split("@")[0] ?? "npm"
    }
  }

=>

  """
  The package manager command (read from package.json "packageManager" field).
  """
  pub packageManager: String! {
    json.field(["packageManager"]).asString.split("@")[0] ?? "npm"
  }
#

this is also making me see the appeal of just letting null propagate - much easier to just write the optimistic code and combine it with a ?? fallback, as opposed to non-null assertions + try/catch