@hasura-ws/model
v1.1.0
Published
Model builder for hasura-ws
Downloads
283
Readme
@hasura-ws/model
A model gives you a basic CRUD
+ subscribe
for your data models
Initialize a model
import { initClient } from '@hasura-ws/browser'
import { initPrepare } from '@hasura-ws/prepare'
import { buildModel } from '@hasura-ws/model'
const client = initClient({
address: 'ws://localhost:8080/v1alpha1/graphql',
token: 'eyJhbGciOiJIUzI...w5c',
})
// if you want react hooks, use initPrepareWithHooks from @hasura-ws/hooks
const prepare = initPrepare(client)
const initModel = buildModel(prepare)
// initModel takes 2 arguments: the table name and the field names
const userModel = initModel('user')(`
email
firstname
lastname
`)
model.add
takes an object of the values to be inserted
// adding a single element
const id = await userModel.add({
email: '[email protected]'
firstname: 'Jean',
lastname: 'Valjean',
})
id // 1
// or an array of elements
const ids = await userModel.add([
{
email: '[email protected]'
firstname: 'Jean',
lastname: 'Valjean',
},
{
email: '[email protected]'
firstname: 'Geraldine',
lastname: 'Mercado',
}
])
ids // [ 1, 2 ]
model.get
takes an id
const user = await userModel.get(1)
user.id // 1
user.email // '[email protected]'
user.firstname // 'Jean'
user.lastname // 'Valjean'
or an array of ids
const users = await userModel.get([1, 2])
users[0].email // '[email protected]'
users[1].email // '[email protected]'
or filter, sort, paginate arguments
getPaginated
the query returns the filtered query
const users = await userModel.getPaginated({
where: { email: { _eq: '[email protected]' } },
offset: 0,
limit: 1,
orderBy: { email: 'asc' },
})
users // [ { email: '[email protected]' } ]
getPaginatedWithCount
the query returns an object with :
- the result of the filtered query - the key of this value is the name of the table queried
- the number of elements returned by this filtered query - the key of this value is always
count
const { user, count } = await userModel.getPaginatedWithCount({
where: { email: { _eq: '[email protected]' } },
offset: 0,
limit: 1,
orderBy: { email: 'asc' },
})
user // [ { email: '[email protected]' } ]
count // 1
getCount
return the count of entries in the table
const count = await userModel.getCount()
count // 2
model.update
takes an object of the changes (including the id)
await userModel.update({ id: 1, email: '[email protected]' })
or a an object of the changes and the id
await userModel.update({ email: '[email protected]' }, 1)
or a an object of the changes and an array of ids
await userModel.update({ email: '[email protected]' }, [1, 2])
model.subscribe
takes a subscription callback and an id
const { execution, unsubscribe } = userModel.subscribe(
user => console.log(user),
1,
)
or an array of ids and a subscription callback
const { execution, unsubscribe } = userModel.subscribe(
users => console.log(users),
[1, 2],
)
model.remove
takes an id
await userModel.remove(1)
or an array of id
await userModel.remove([1, 2])