# API
# Module Exports
The vue-postgrest module exports a plugin, a mixin and several helper functions and classes.
# VuePostgrest - Plugin
Type:
VuePluginUsage:
Installing the plugin registers the instance method $postgrest on your Vue instance. See available plugin options.
WARNING
You have to install the plugin in any case, even if you only use the mixin in your components!
Example:
import Vue from 'vue' import VuePostgrest from 'vue-postgrest' Vue.use(VuePostgrest)
# pg - Mixin
Type:
VueMixinUsage:
Import the
pgmixin and include it in your component'smixinattribute. The component has to provide apgConfigobject specifying the mixin options.Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: { select: ['id' 'name', 'age'] } } } }, onError (err) { console.log(err) } }
# resetSchemaCache()
Type:
FunctionArguments:
Returns:
undefinedUsage:
Reset the schema cache, i.e. the inverse of
$postgrest.$ready. Useful in unit tests.
# setDefaultToken(token)
Type:
FunctionArguments:
{string} token
Returns:
undefinedUsage:
Set the default access token used for all authentication with the API. Sets the appropriate
Authorizationheader.TIP
You can override the token locally by setting the corresponding component prop or mixin option.
Example:
import { setDefaultToken } from 'vue-postgrest' export default { name: 'App', async mounted: { // authenticate by calling a stored procedure const resp = await this.$postgrest.rpc('authenticate') // parsing fetch response body to json const token = await resp.json() // setting default access token globally setDefaultToken(token) } }
# usePostgrest(apiRoot, token)
Type:
FunctionArguments:
{string} apiRoot{string} token
Returns:
SchemaUsage:
Used to create a new schema for the specified baseUri with the specified default auth token. If
apiRootis undefined, the apiRoot of the existing Schema is used.The returned value is the same as
this.$postgrestand can be used without the vue instance, e.g. in a store module.
# AuthError
Instances of AuthError are thrown when the server rejects the authentication token.
# SchemaNotFoundError
Instances of SchemaNotFoundError are thrown, when there is no valid postgrest schema at the base URI.
# FetchError
Instances of FetchError are thrown on generic errors from Fetch that don't trigger the throw of more specific errors.
# PrimaryKeyError
Instances of PrimaryKeyError are thrown, when no primary keys are found for the specified route on the schema or no valid primary key is found on a GenericModel.
# Plugin Options
Global options can be set when initializing Vue-Postgrest with Vue.use.
# apiRoot
Type:
StringDefault:
''Details:
The URI used as the base for all requests to the API by the mixin, global and local components, as well as the global vue-postgrest instance. This should be the URI to your PostgREST installation.
TIP
You can override the base URI locally by setting the component prop or mixin option.
Example:
import VuePostgrest from 'vue-postgrest' Vue.use(VuePostgrest, { apiRoot: '/api/' })
# headers
Type:
ObjectDefault:
{}Details:
A key/value mapping of default headers to send with each request.
Example:
import VuePostgrest from 'vue-postgrest' Vue.use(VuePostgrest, { apiRoot: '/api/', headers: { Prefer: 'timezone=' + Intl.DateTimeFormat().resolvedOptions().timeZone } })
# Mixin Options
Mixin options are set in the component using the pg mixin by setting the pgConfig object on the component instance.
# apiRoot
Type:
StringDefault: Global plugin option
Details:
The URI used as the base for all requests to the API by the mixin, global and local components, as well as the global vue-postgrest instance. This should be the URI to your PostgREST installation.
TIP
This overrides the global plugin option!
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { apiRoot: '/another-api/' } } } }
# route required
Type:
StringDetails:
The table/view that is queried.
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'clients' } } } }
# token
Type:
StringDefault:
undefinedDetails:
The access token used for authorizing the connection to the API. This options sets the
Authorizationheader for all requests.See also Client Auth (opens new window) in the PostgREST documentation.
TIP
You can set this globally with the setDefaultToken method!
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', token: 'YOUR_API_TOKEN' } } } }
# query
Type:
ObjectDefault:
undefinedDetails:
The query sent to the API is constructed from this option. See the Query API as well as API (opens new window) in the PostgREST documentation for more details.
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: { select: ['id', 'name', 'address'], and: { 'name.not.eq': 'Tion Medon', 'city.eq': 'Pau City', 'age.gt': 150 } } } } } }
# single
Type:
BooleanDefault:
falseDetails:
If set to true, the request will be made with the
Accept: application/vnd.pgrst.object+jsonheader andthis.pgwill be of type GenericModel. If set to false (the default), the header will beAccept: application/jsonandthis.pgwill be of type GenericCollection.See also Singular or Plural (opens new window) in the PostgREST documentation.
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: { 'id.eq': 1 }, single: true } } } }
# limit
Type:
NumberDefault:
undefinedDetails:
Limits the count of response items by setting
Range-UnitandRangeheaders. Only used whensingle: falseis set.See also Limits and Pagination (opens new window) in the PostgREST documentation.
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: { 'age.gt': 150 }, // get the first 10 inhabitants that pass the filter query limit: 10 } } } }
# offset
Type:
NumberDefault:
undefinedDetails:
Offset the response items, useful e.g. for pagination, by setting
Range-UnitandRangeheaders. Only used whensingle: falseis set.See also Limits and Pagination (opens new window) in the PostgREST documentation.
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: { 'age.gt': 150 }, // get all inhabitants that pass the filter query, starting from no. 5 offset: 5 } } } }
# count
Type:
StringDefault:
undefinedOptions:
exactplannedestimated
Details:
Only used when
single: falseis set.See PostgREST docs for details on those options:
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: { 'age.gt': 150 }, count: 'exact' } } } }
# Mixin Hooks
Hooks are called on the component instance that uses the pg mixin.
# onError
Type:
FunctionArguments:
{FetchError | AuthError} error
Details:
Called when a FetchError or AuthError occurs. The Hook gets passed the error object.
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: {} } } }, onError (err) { // an error occured! console.log(err) } }
# Mixin Properties
Using the pg mixin exposes this.pg with the following properties.
# pg
Type:
GenericCollection | GenericModelDetails:
Dependent on the
pgConfig.singlesetting this is either of type GenericCollection or GenericModel. A GenericCollection is essentially just an Array of GenericModels with some additional methods. Both types have apg.$get()method available to manually refresh the request.Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: {} } } }, computed: { inhabitants () { return this.pg } } }
# Instance Methods
The instance method vm.$postgrest is available on your Vue Instance after installing the plugin.
# $postgrest
Type:
RouteArguments:
{string} apiRoot{string} token
Returns:
SchemaThrows:
SchemaNotFoundErrorUsage:
Used to create a new schema for the specified baseUri with the specified default auth token. If
apiRootis undefined, the apiRoot of the existing Schema is used.
# $postgrest[route]
Type:
RouteThrows:
AuthError | FetchErrorUsage:
After the schema is ready, all available routes are exposed on the $postgrest instance. The exposed
Routeaccepts the following arguments:{string} methodone of'OPTIONS','GET','HEAD','POST','PATCH','PUT'or'DELETE'{object} querysee Query{object} optionsadditional options, see below{object} bodypayload for post/patch/put requests
Available options are:
{string} acceptAcceptheader to set or one of the options 'single', 'binary' or 'text', which set the header automatically. Default header is 'application/json'.{number} limitLimit the response to no. of items by setting theRangeandRange-Unitheaders{number} offsetOffset the response by no. of items by setting theRangeandRange-Unitheaders{string} returnSetreturn=[value]part ofPreferheader{string} paramsSetparams=[value]part ofPreferheader{string} countSetcount=[value]part ofPreferheader{string} resolutionSetresolution=[value]part ofPreferheader{object} headersOverwrite headers. Keys are header field names, values are strings.
The
Routeinstance provides convencience methods for calling the following HTTP requests directly, omit themethodargument in this case:$postgrest.route.options([query, options])$postgrest[route].get([query, options])$postgrest[route].head([query, options])$postgrest[route].post([query, options, body])$postgrest[route].patch([query, options, body])$postgrest[route].put([query, options, body])$postgrest[route].delete([query, options])
Example:
export default { name: 'Galaxy', data () { return { planets: undefined, cities: undefined } } async mounted: { // wait for the schema to be ready await this.$postgrest.$ready const planetsResp = await this.$postgrest.planets('GET') const citiesResp = await this.$postgrest.cities.get() this.planets = await planetsResp.json() this.cities = await citiesResp.json() } }
# $postgrest.$ready
Type:
PromiseThrows:
SchemaNotFoundErrorUsage:
The promise resolves, when the schema was successfully loaded and rejects if no valid schema was found.
Example:
export default { name: 'Component', async mounted: { // wait for the schema to be ready try { await this.$postgrest.$ready } catch (e) { console.log('Could not connect to API...') } } }
# $postgrest.$route(route)
Type:
FunctionArguments:
{string} route
Returns:
RouteUsage:
Use this function, if you have to access a route, before the schema is ready and the routes have been exposed on the $postgrest instance. Returns a
Routefor the specified route.Example:
export default { name: 'Cities', methods: { async getCities () { return this.$postgrest.$route('cities').get() }, async addCity () { await this.$postgrest.$route('cities').post({}, {}, { name: 'Galactic City' }) } } }- See also: $postgrest[route]
# $postgrest.rpc[function-name]
Type:
RPCUsage:
After the schema is ready, all available stored procedures are exposed on $postgrest.rpc[function-name] and can be called like this:
$postgrest.rpc[function-name]([params, options]).The
paramsobject contains parameters that are passed to the stored procedure.Available
optionsare:{boolean} getset request method to 'GET' if true, otherwise 'POST'{string} acceptAcceptheader to set or one of the options 'single', 'binary' or 'text', which set the header automatically. Default header is 'application/json'.{object} headersProperties of this object overwrite the specified header fields of the request.
Example:
export default { name: 'Component', methods: { async destroyAllPlanets () { // wait till schema is loaded await this.$postgrest.$ready const result = await this.$postgrest.rpc.destroyplanets({ countdown: false }, { accept: 'text', headers: { 'Warning': 'Will cause problems!' } }) if (await result.text() !== 'all gone!') { this.$postgrest.rpc.destroyplanets({ force: true }) } } } }
# $postgrest.rpc(function-name[, params, options])
Type:
FunctionThrows:
AuthError | FetchErrorArguments:
{string} function-name{object} params{object} options
Returns: API response
Usage:
Calls a stored procedure on the API.
function-namespecifies the stored procedure to call. Forparamsandoptionssee $postgrest.rpcExample:
export default { name: 'Component', methods: { async destroyAllPlanets () { await this.$postgrest.rpc('destroyplanets', { countdown: false }, { accept: 'text', headers: { 'Warning': 'Will cause problems!' } }) } } }
# Component Props
The <postgrest> component accepts all mixin options as props, see above for details.
- Example:
<template>
<postgrest
route="planets"
:query="{}"
single
limit="10">
</template>
# Component Slot Scope
The <postgrest> component provides the pg mixin property as scope in the default slot, see above for details.
Example:
<template> <postgrest route="planets" :query="{}"> <template v-slot:default="planets"> <loading v-if="planets.$get.isPending"/> <ul v-else> <li v-for="planet in planets" :key="planet.id"> {{ planet.name }} </li> </ul> </template> </template>
# Component Events
# error
Type:
EventPayload:
AuthError | FetchErrorUsage:
This event is emitted when an AuthError or FetchError occurs.
Example:
<template> <postgrest route="planets" :query="{}" @error="handleError"> <template v-slot:default="planets"> <loading v-if="planet.$get.isPending"/> <ul v-else> <li v-for="planet in planets" :key="planet.id"> {{ planet.name }} </li> </ul> </template> </template> <script> import { AuthError } from 'vue-postgrest' export default { name: 'PlanetsList', methods: { handleError (e) { if (e instanceof AuthError) { console.log('Something wrong with the token!') } else { throw e } } } } </script>
# GenericCollection
A GenericCollection is essentially an Array of GenericModels and inherits all Array methods. The following additional methods and getters are available:
# $get([options])
Type:
ObservableFunctionArguments:
{object} options
Returns: Response from the API
Throws:
AuthError | FetchErrorDetails:
An ObservableFunction for re-sending the get request. All Options described in postgrest route are available here as well, except for the
acceptoption.Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: {} } } }, methods: { refresh () { this.pg.$get() if (this.pg.$get.isPending) { console.log('Get still pending...') } else { console.log('Fetched inhabitants: ', this.pg) } } } }
# $new(data)
Type:
FunctionArguments:
{object} data
Returns:
GenericModelDetails:
Creates and returns a new GenericModel, which can be used for a $post() call.
Example:
import { pg } from 'vue-postgrest' export default { name: 'HeroesList', mixins: [pg], data () { return { newItem: null, pgConfig: { route: 'heroes' } } }, mounted () { this.newItem = this.pg.$new({ name: 'Yoda', age: 999999999 }) }, methods: { addHero () { this.newItem.$post() } } }
# $range
Type:
ObjectProvided if: API response sets
Content-RangeheaderProperties:
{number} firstfirst retrieved item{number} lastlast retrieved item{number} totalCounttotal number of retrieved items, undefined ifcountis not set
Details:
An object describing the result of server-side pagination.
Example:
import { pg } from 'vue-postgrest' export default { name: 'Component', mixins: [pg], data () { return { pgConfig: { route: 'inhabitants', query: { 'age.gt': 150 }, offset: 5, limit: 10, count: 'estimated' } } }, computed: { firstItem () { // first retrieved item return this.pg.$range.first }, lastItem () { // last retrieved item return this.pg.$range.last }, totalCount () { // total number of retrieved items, undefined if option count is not set return this.pg.$range.totalCount } } }
# GenericModel
The data of a GenericModel is available directly on the instance in addition to the following methods and getters:
# $get([options])
Type:
ObservableFunctionArguments:
{object} options
Returns: Response from the API
Throws:
AuthError | FetchError | PrimaryKeyErrorDetails:
An ObservableFunction for a get request. Available
optionsare:{boolean} keepChangesIf true, local changes to the model are protected from being overwritten by fetched data and only unchanged fields are updated.All Options described in postgrest route are available here as well. Note: The
acceptoption is not valid here - theAcceptheader will always be set to'single'if not overwritten via theheadersobject.
Example:
import { pg } from 'vue-postgrest' export default { name: 'UserProfile', mixins: [pg], data () { return { pgConfig: { route: 'users', query: { 'id.eq': this.$store.getters.userId }, single: true } } }, methods: { reloadUser () { this.pg.$get() } } }
# $post([options])
Type:
ObservableFunctionArguments:
{object} options
Returns: Response from the API
Throws:
AuthError | FetchErrorDetails:
An ObservableFunction for a post request. Available
optionsare:{array<string>} columnsSetscolumnsparameter on request to improve performance on updates/inserts{string} returnAddreturn=[value]header to request. Possible values are'representation'(default) and'minimal'.All Options described in postgrest route are available here as well. Note: The
acceptoption is not valid here - theAcceptheader will always be set to'single'if not overwritten via theheadersobject.
If option
returnis set to'representation', which is the default value, the model is updated with the response from the server.If option
returnis set to'minimal'and theLocationheader is set, the location header is returned as an object.Example:
import { pg } from 'vue-postgrest' export default { name: 'HeroesList', mixins: [pg], data () { return { newHero: null, pgConfig: { route: 'heroes' } } }, mounted () { this.newHero = this.pg.$new({ name: 'Yoda', age: 999999999 }) }, methods: { addHero () { this.newHero.$post() } } }
# $put([options])
Type:
ObservableFunctionArguments:
{object} options
Returns: Response from the API
Throws:
AuthError | FetchError | PrimaryKeyErrorDetails:
An ObservableFunction for a put request. Available
optionsare:{array<string>} columnsSetscolumnsparameter on request to improve performance on updates/inserts{string} returnAddreturn=[value]header to request. Possible values are'representation'(default) and'minimal'.All Options described in postgrest route are available here as well. Note: The
acceptoption is not valid here - theAcceptheader will always be set to'single'if not overwritten via theheadersobject.
If option
returnis set to'representation', which is the default value, the model is updated with the response from the server.If option
returnis set to'minimal'and theLocationheader is set, the location header is returned as an object.Example:
import { pg } from 'vue-postgrest' export default { name: 'HeroesList', mixins: [pg], data () { return { newHero: null, pgConfig: { route: 'heroes' } } }, mounted () { this.newHero = this.pg.$new({ name: 'Yoda', age: 999999999 }) }, methods: { upsertHero () { // Assuming "name" is the primary key, because PUT needs a PK set this.newHero.$put() } } }
# $patch([options, data])
Type:
ObservableFunctionArguments:
{object} options{object} data
Returns: Response from the API
Throws:
AuthError | FetchError | PrimaryKeyErrorDetails:
An ObservableFunction for a patch request. The patch function also accepts an object as first argument with fields that should be patched, properties declared in this object take precedence over fields changed on the model directly. Available
optionsare:{array<string>} columnsSetscolumnsparameter on request to improve performance on updates/inserts{string} returnAddreturn=[value]header to request. Possible values are'representation'(default) and'minimal'.All Options described in postgrest route are available here as well. Note: The
acceptoption is not valid here - theAcceptheader will always be set to'single'if not overwritten via theheadersobject.
If option
returnis set to'representation', which is the default value, the model is updated with the response from the server.Example:
import { pg } from 'vue-postgrest' export default { name: 'HeroProfile', mixins: [pg], data () { return { pgConfig: { route: 'heroes', query: { 'name.eq': 'Yoda' }, accept: 'single' } } }, methods: { updateHeroAge (age) { this.pg.age = age this.pg.$patch({}, { name: 'Younger Yoda '}) // sends a patch request with the data: { age: age, name: 'Younger Yoda' } } } }
# $delete([options])
Type:
ObservableFunctionArguments:
{object} options
Returns: Response from the API
Throws:
AuthError | FetchError | PrimaryKeyErrorDetails:
An ObservableFunction for a delete request. Available
optionsare:{string} returnAddreturn=[value]header to request. Possible values are'representation'and'minimal'.All Options described in postgrest route are available here as well. Note: The
acceptoption is not valid here - theAcceptheader will always be set to'single'if not overwritten via theheadersobject.
If option
returnis set to'representation', the model is updated with the response from the server.Example:
import { pg } from 'vue-postgrest' export default { name: 'HeroProfile', mixins: [pg], data () { return { pgConfig: { route: 'heroes', query: { 'name.eq': 'Yoda' }, single: true } } }, methods: { deleteYoda () { // oh, no! this.pg.$delete() } } }
# $isDirty
Type:
BooleanDetails:
Indicating whether the model data has changed from its initial state.
Example:
import { pg } from 'vue-postgrest' export default { name: 'HeroProfile', mixins: [pg], data () { return { pgConfig: { route: 'heroes', query: { 'name.eq': 'Yoda' }, single: true } } }, methods: { updateHero () { if (this.pg.$isDirty) { this.pg.$patch() } } } }
# $reset()
Type:
FunctionDetails:
Reset the model data to it's initial state.
Example:
import { pg } from 'vue-postgrest' export default { name: 'HeroProfile', mixins: [pg], data () { return { pgConfig: { route: 'heroes', query: { 'name.eq': 'Yoda' }, accept: 'single' } } }, methods: { changeAge (age) { this.pg.age = age }, resetHero () { this.pg.$reset() } } }
# ObservableFunction
An ObservableFunction has the following Vue-reactive properties indicating it's current status.
# clear([error|index, ...])
Type:
FunctionArguments:
- any number of type
ErrororNumber
- any number of type
Returns: Nothing
Details:
Removes errors from the
.errorsproperty.clear(error, ...)removes specific errors by reference.clear(index, ...)removes specific errors by index.clear()removes all errors and resets.hasReturned.try { this.pg.$delete() } catch (e) { if (e instanceof AuthError) { this.handleAuthError() this.pg.$delete.clear(e) } else { // error e.g. rendered in template } }
# errors
Type:
Array<Error>Details:
An Array of Errors that are associated with this Function. This is cleared automatically upon the next successful request or manually with
ObservableFunction.clear().
# hasError
Type:
BooleanDetails:
Indicating whether there were errors during the request. This is cleared automatically upon the next successful request or manually with
ObservableFunction.clear().
# hasReturned
Type:
BooleanDetails:
Indicating whether the request has returned successfully at least once. Useful to differentiate between "first load" and "refresh" in conjunction with
ObservableFunction.isPending. This can be reset to false manually by callingObservableFunction.clear()without arguments.
# isPending
Type:
BooleanDetails:
Indicating whether there are pending calls for this Function.
# pending
Type:
Array<AbortController>Details:
This array holds an
AbortControllerinstance for every function call that is currently pending. Those are passed to the underlyingfetch()call for requests and can be used to cancel the request. See AbortController (MDN) (opens new window) for details.