tinybase icon indicating copy to clipboard operation
tinybase copied to clipboard

Add `required` property to schema definitions

Open bholmesdev opened this issue 1 year ago • 3 comments

Is your feature request related to a problem? Please describe.

I've been using schemas for typed queries on my store. The tooling is excellent, but I was surprised to find "not null" checks are required for all fields. I understand this is a design decision to keep TinyBase flexible. However, I expected a required property to be supported on schemas to assert values are not null when adding entries.

store.setTablesSchema({
  pets: {
    species: {type: 'string'},
    legs: {type: 'number', default: 4},
    sold: {type: 'boolean', default: false},
  },
}).addRow('pets', {
  // all values can be undefined here
});

Describe the solution you'd like

I'd like to see a required property on schema definitions to enforce defined fields. I'd expect this to be a boolean value alongside type and default:

store.setTablesSchema({
  pets: {
    species: {
      type: 'string',
+     required: true,
    },
    legs: {type: 'number', default: 4},
    sold: {type: 'boolean', default: false},
  },
});

Describe alternatives you've considered I've asserted that all values are not-null when adding or updating entries. This gets quite noisy when using TypeScript.

Additional context I recall hearing required was supported when listening to your interview on the Local-first podcast (great stuff by the way!). However, I haven't been able to find this in the documentation or by attempting to add required in my code.

bholmesdev avatar Aug 22 '24 22:08 bholmesdev

Hey @bholmesdev! My original intention was that the presence of default implicitly also means required - in other words, a value always has to be there, and if you don't supply it, then the required value will be used.

Of the top of my head, if you provide an entirely empty object, I don't think it will constitute a whole default row for you. (If not maybe it should).

It's also possible I messed up the schema-inferred typing though. Let me noodle on this for a bit.

jamesgpearce avatar Aug 25 '24 14:08 jamesgpearce

Still new to tinybase (also localfirst listener!) - does this apply to the read/query side too?

"noUncheckedIndexedAccess": false - would allow a Row.field to be of type Cell as opposed to Cell | undefined

Sadly noUncheckedIndexedAccess is not something any serious ts project should be disabling. The type signature on Cell would indicate that default doesn't really impact anything on the query side?

dpnova avatar Mar 20 '25 22:03 dpnova

I'm also in need to requiring that a value is provided when creating the a row in a table, and it doesn't make sense for that value to assume a default if the value wasn't provided. It's a consumer error to not pass it in, so I'd prefer that it throws if that the value wasn't provided.

marcusstenbeck avatar Apr 29 '25 05:04 marcusstenbeck