Is it possible to simplify the use of DocumentReference and Document?

Currently I set-up references with the type DocumentReference + collection type => user: User | DocumentReference. That’s because using user: User works perfectly for fetching data from Fauna with projection. But as soon I need to deal with references (e.g. while creating new documents), I need DocumentReference. Is it somehow possible to simplify this to have only one?

type User = {
	sessions: User[] | DocumentReference[]
};

type Session = {
	user: User | DocumentReference; // Can this somehow simplified?
};

And another Question:
Is it possible to scope DocumentReference to a Collection? Something like DocumentReference<User>

You could use projection when creating new documents so that the payload shape is the same. Otherwise, you are choosing to return one of two different types, and your type User | DocumentReference seems appropriate.

I don’t know if it will help you, but the driver provides a type definition DocumentT, which might be somewhat applicable. fauna-js/src/values/doc.ts at f6ab840b3c4bcc5d6e74406effdaa69137f5125b · fauna/fauna-js · GitHub

type DocumentT<T extends QueryValueObject> = Document & T;

Now, projection turns an FQL Document type into a plain object. It’s not clear if you are actually returning an actual Document for a Session or User. The driver will only deserialize the query results to a Javascript Document instance if the query returns a Document as opposed to a projected object. You can however, create an instance yourself; the constructor is designed to accept a plain object that contains the id, coll and ts fields. You can validate the result by checking instanceof Document or instanceof DocumentReference

In any case, if you are choosing to return different shaped payloads from different request, then you are going to need to handle a union of types. That’s not a Fauna thing.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.