Fauna-js Typescript snippets

This shall be a collection of Typescript snippets for different use cases that hopefully make the start of some of you guys a bit easier.
Status: In progress

Fetch multiple documents

Example: User.all()

Variant 1

Set-up

import { Client, fql, Page, type QuerySuccess, type DocumentT } from 'fauna';

const client = new Client({
	secret: <YOUR_FAUNA_KEY>
});

type User = {
	name: string;
};

Typed code

const response: QuerySuccess<Page<DocumentT<User>>> = await client.query<Page<DocumentT<User>>>(fql`User.all()`);

const page: Page<DocumentT<User>> = response.data;

const data: Array<DocumentT<User>> = page.data

Variant 2

Replace DocumentT with Document and an intersection.
Set-up

import { Client, fql, Module, Page, Document, type QuerySuccess} from 'fauna';

const client = new Client({
	secret: <YOUR_FAUNA_KEY>
});

type User = Document & {
	name: string;
};

Typed code

const response: QuerySuccess<Page<User>> = await client.query<Page<User>>(
		fql`User.all()`
	);

const page: Page<User> = response.data;

const data: User[] = page.data

Fetch one document

Example: User.all().first()

Variant 1

Set-up

import { Client, fql, type QuerySuccess, type DocumentT } from 'fauna';

const client = new Client({
	secret: <YOUR_FAUNA_KEY>
});

type User = {
	name: string;
};

Typed code

const response: QuerySuccess<DocumentT<User>> = await client.query<DocumentT<User>>(fql`User.all().first()`);
const data: DocumentT<User> = response.data;

Variant 2

Replace DocumentT with Document and an intersection.typed documents
Set-up

import { Client, fql, Module, Document, type QuerySuccess} from 'fauna';

const client = new Client({
	secret: <YOUR_FAUNA_KEY>
});

type User = Document & {
	name: string;
};

Typed code

const response: QuerySuccess<User> = await client.query<User>(fql`User.all().first()`);
const data: User = response.data;

Create Document

Update Document

2 Likes