63 |
64 | ```
65 |
66 | Using the mixin option `single: true` will set the `Accept` header to tell PostgREST to return a single item unenclosed by an array. In this case you can use `this.pg` to access the returned item directly.
67 |
68 | The mixin option `query` is used to construct the PostgREST query string. Use `query.select` for column filtering like this:
69 |
70 | ``` vue
71 |
80 | ```
81 |
82 | The select key alternatively accepts an object with column names as keys. You can use aliasing and casting like this:
83 |
84 | ``` vue
85 |
98 | ```
99 |
100 | ### Ordering
101 |
102 | To order your response, you can either pass an array of strings or an object to `query.order`. E.g.:
103 |
104 | ``` vue
105 |
113 |
114 | // or
115 |
116 |
127 | ```
128 |
129 | ### Row Filtering
130 |
131 | The `query` constructs column conditions from it's keys. Operators are dot-appended to the key.
132 | E.g. to use multiple conditions:
133 |
134 | ``` vue
135 |
144 | ```
145 |
146 | When passing arrays, the resulting query string is constructed based on the used operator! See [Arrays](../query/#arrays). Furthermore, `undefined` values will exclude the column condition from the query string - this can be useful if you create your query object dynamically.
147 |
148 |
149 | ::: tip
150 | For convenient creation of range objects see [Range Objects](../query/#range-objects)!
151 | :::
152 |
153 | ### Embedding
154 |
155 | PostgREST offers an easy way to handle relationships between tables/views. You can leverage this by using the embed syntax in your queries. The syntax to filter, order or select embeds corresponds to the root level of the query object:
156 |
157 | ``` vue
158 |
173 | ```
174 |
175 | **Important:** If you omit the `select` key in an embed object, it is assumed that you want to access a JSON-field instead of embedding a resource! See [JSON Columns](../query/#json-columns) for details.
176 |
177 | ### Loading / Refreshing
178 |
179 | For monitoring the current status of the request, you can use `this.pg.$get` which is an [ObservableFunction](../api/#observable-function). `pg.$get.isPending` tells you, if a request is still pending:
180 |
181 | ``` vue
182 |
183 |
184 |
185 |
{{ hero.name }}
186 |
187 |
188 | ```
189 |
190 | You can call the `$get` function to rerun the get request, e.g. if you need to refresh your data manually.
191 |
192 | **Note:** The `$get` function also exposes getters for information about failed requests, see [error handling](./#error-handling).
193 |
194 | ### Pagination
195 |
196 | Server side pagination can be achieved by setting the mixin options `limit` and `offset`. When used as a mixin option (or component prop), these options set the appropriate request headers automatically. When used inside a query object, limit and offset will be appended to the query string.
197 |
198 | **Range**
199 | To get information about the paginated response, the mixin provides the `pg.$range` object, based on the response's `Content-Range` header. To get the total count of available rows, use the mixin option `count = 'exact'` which sets the corresponding `Prefer` header.
200 |
201 | ``` vue
202 |
203 | ...
204 | Displaying hero no. {{ pg.$range.first }} to {{ pg.$range.last }} of {{ pg.$range.totalCount }} total Heroes
205 |
206 |
207 | ...
208 |
209 |
210 |
235 | ```
236 |
237 | ### Multiple Requests
238 |
239 | Sometimes it may be necessary to access multiple tables/views or query the same route twice the from the same component. You can use the `postgrest` component for this.
240 |
241 | The component takes the same options as the `pg` mixin as props and provides it's scope as slot props, so you can use it in your template like this:
242 |
243 | ``` vue
244 |
245 |
246 |
247 |
257 |
258 |
259 |
260 | Our new heroes are {{ heroes[0].name }} and {{ heroes[1].name }}!
261 |
262 |
263 |
264 |
265 |
266 |
267 |
{{ hero.name }}
268 |
269 |
270 |
271 | ```
272 |
273 | **Note:** If you encounter situations where it is more convenient to do this programmatically, you can also use instance methods! The `this.$postgrest` exposes a [Route](../api/#postgrest-route) for each table/view that is available in your schema. You could then rewrite the above example like this:
274 |
275 | ``` vue
276 |
277 |
278 |
279 |
280 | Our new heroes are {{ latestHeroes[0].name }} and {{ latestHeroes[1].name }}!
281 |
282 |
283 | ...
284 |
285 |
286 |
287 |
319 | ....
320 | ```
321 |
322 | ## Modifying Data
323 |
324 | Each item provided by the mixin or the component is a [Generic Model](../api/#genericmodel), which is a wrapper for the entity received from the server with some added methods and getters.
325 |
326 | Getting an item, modifying it's data and patching it on the server can be as simple as:
327 |
328 | ``` vue
329 |
330 | ...
331 |
332 | ...
333 |
334 |
335 |
352 | ```
353 |
354 | ::: warning
355 | The instance methods `$postgrest.ROUTE.METHOD` do not wrap the response in GenericModels but return the fetch `Response` directly.
356 | :::
357 |
358 | ### Model State
359 |
360 | Just like the mixin method `pg.$get`, the request-specific methods provided by a GenericModel are [ObservableFunctions](../api/#observablefunction). This means, you can check on the status of pending requests or errors via the respective getters. In addition, GenericModels provide the getter `model.$isDirty`, which indicates if the model's data changed from it's initial state, as well as a `model.$reset()` method, which resets the data to it's initial state.
361 |
362 | **Note:** The model is updated after $patch requests by default and `initial state` is set to the updated data. If you don't want to update the model, e.g. when doing a partial patch, set the `$patch` option `return='minimal'`.
363 |
364 | The first argument to the `model.$patch` method is an options object. The second argument to `$patch` is an object with additional patch data. See [$patch](../api/#patch-data-options) for details.
365 |
366 | A more extensive example could look like this:
367 |
368 | ``` vue
369 |
370 | ...
371 |
430 |
431 |
432 | ...
433 |
434 |
435 |
444 | ```
445 |
446 | ## Creating Models
447 |
448 | When the mixin option `single` is `false` (the default) `this.pg` is actually an instance of a [GenericCollection](../api/#genericcollection). The `GenericCollection` has a method `pg.$new(...)` to create new `GenericModel`s. You can then call `$post()` on the returned models to make a `POST` request.
449 |
450 | ``` vue
451 |
452 | ...
453 |
454 | Create new Hero
455 | ...
456 |
457 |
458 |
485 | ```
486 |
487 | ### Upserts
488 |
489 | You can do an upsert (insert or update, when it already exists) with either a `POST` or a `PUT` request. To make a `PUT` request, just call `$put()` on the model - but make sure to set the primary key on the model first.
490 |
491 | Alternatively, you can use all options that a [route](../api/#postgrest-route) offers with `$post()`. To perform an upsert, you can pass the `resolution` option, which sets the resolution part of the `Prefer` header. To set the `on_conflict` query string parameter, see [Query](../query/#on-conflict).
492 |
493 | Example for `$post()` upsert:
494 |
495 | ``` vue
496 |
497 | ...
498 |
499 | Create Hero
500 | ...
501 |
502 |
503 |
527 | ```
528 |
529 | ## Handling Errors
530 |
531 | ### Mixin / Component
532 |
533 | The mixin calls the `onError` hook on your component instance whenever a [FetchError](../api/#fetcherror) or an [AuthError](../api/#autherror) is thrown. To react to errors from the `postgrest` component, use the `error` event. The error object is passed to the hook/event.
534 |
535 | ### GenericModel / Instance Methods / Stored Procedures
536 |
537 | All request-specific methods from a [GenericCollection](../api/#genericcollection) or [GenericModel](../api/#genericmodel), as well as the [instance methods](../api/#instancemethods) and [stored procedure calls](../api/#postgrest-rpc-function-name-options-params) throw [AuthError](../api/#autherror) and [FetchError](../api/#fetcherror).
538 | Additionally, the generic model methods throw [PrimaryKeyError](../api/#primarykeyerror).
539 |
540 | ::: tip
541 | You can test whether a schema was found for the base URI by catching [SchemaNotFoundError](../api/#schemanotfounderror) on [$postgrest.$ready](../api/#postgrest-ready).
542 | :::
543 |
544 | ### Full Example
545 |
546 | ``` vue
547 |
548 |
549 |
553 |
554 | Could not load vehicles...
555 |
556 |
557 |
558 |
559 |
560 |
561 |
562 |
563 |
564 |
565 |
566 |
567 |
622 | ```
623 |
624 | ## Stored Procedures
625 |
626 | For calling stored procedures, the instance method `$postgrest.rpc` is provided. On loading the schema, all available stored procedures are registered here. The stored procedure call accepts an object containing the parameters that are passed to the stored procedure and an options object. By default, RPCs are called with the request method `POST`, you can set the rpc option `get: true` if you want to call a RPC with `GET` instead. For setting the `Accept` header, use the option `accept`.
627 |
628 | ``` vue
629 |
647 | ```
648 |
649 | ::: tip
650 | If you want to call a RPC before the schema is loaded, you can call `$postgrest.rpc` directly by passing the name of the stored procedure that should be called as the first argument, followed by the rpc parameters and options. See [RPC](../api/#postgrest-rpc-function-name-options-params) for details.
651 | :::
652 |
653 | ## Authentication
654 |
655 | The most convenient way to set the `Authorization` header to include your jwt token is to use the [setDefaultToken](../api/#setdefaulttoken) method exported by the module. This method sets the token to use for all subsequent communication with the PostgREST server.
656 |
657 | ``` vue
658 | import { setDefaultToken } from 'vue-postgrest'
659 |
660 |
667 | ```
668 |
669 | If you want to overwrite the token used for specific requests, you can either use the mixin option `token` or the component prop, respectively.
670 |
671 | To handle rejected requests due to token errors, use the `AuthError` that is thrown when the server rejects your token, see [Handling Errors](./#handling-errors) for details.
672 |
673 | ::: tip
674 | You can use the instance method `$postgrest` to create a new schema. If you set the first argument (`apiRoot`) to undefined, a new schema is created with the base URI used by the default schema. You can pass an auth token as the second argument, which will then be used for subsequent requests with the new schema.
675 | :::
676 |
--------------------------------------------------------------------------------
/docs/api/index.md:
--------------------------------------------------------------------------------
1 | # API
2 |
3 | ## Module Exports
4 |
5 | The `vue-postgrest` module exports a plugin, a mixin and several helper functions and classes.
6 |
7 | ### VuePostgrest - Plugin
8 |
9 | - **Type:** `VuePlugin`
10 |
11 | - **Usage:**
12 |
13 | Installing the plugin registers the instance method $postgrest on your Vue instance. See available [plugin options](./#plugin-options).
14 |
15 | ::: warning
16 | You have to install the plugin in any case, even if you only use the mixin in your components!
17 | :::
18 |
19 | - **Example:**
20 |
21 | ``` js
22 | import Vue from 'vue'
23 | import VuePostgrest from 'vue-postgrest'
24 |
25 | Vue.use(VuePostgrest)
26 | ```
27 |
28 | ### pg - Mixin
29 |
30 | - **Type:** `VueMixin`
31 |
32 | - **Usage:**
33 |
34 | Import the `pg` mixin and include it in your component's `mixin` attribute. The component has to provide a `pgConfig` object specifying the [mixin options](./#mixin-options).
35 |
36 | - **Example:**
37 |
38 | ``` js
39 | import { pg } from 'vue-postgrest'
40 |
41 | export default {
42 | name: 'Component',
43 | mixins: [pg],
44 | data () {
45 | return {
46 | pgConfig: {
47 | route: 'inhabitants',
48 | query: {
49 | select: ['id' 'name', 'age']
50 | }
51 | }
52 | }
53 | },
54 | onError (err) {
55 | console.log(err)
56 | }
57 | }
58 | ```
59 |
60 | ### resetSchemaCache()
61 |
62 | - **Type:** `Function`
63 |
64 | - **Arguments:**
65 |
66 | - **Returns:** `undefined`
67 |
68 | - **Usage:**
69 |
70 | Reset the schema cache, i.e. the inverse of `$postgrest.$ready`. Useful in unit tests.
71 |
72 | ### setDefaultToken(token)
73 |
74 | - **Type:** `Function`
75 |
76 | - **Arguments:**
77 | - `{string} token`
78 |
79 | - **Returns:** `undefined`
80 |
81 | - **Usage:**
82 |
83 | Set the default access token used for all authentication with the API. Sets the appropriate `Authorization` header.
84 |
85 | ::: tip
86 | You can override the token locally by setting the corresponding [component prop](./#component-props) or [mixin option](./#token).
87 | :::
88 |
89 | - **Example:**
90 |
91 | ``` js
92 | import { setDefaultToken } from 'vue-postgrest'
93 |
94 | export default {
95 | name: 'App',
96 | async mounted: {
97 | // authenticate by calling a stored procedure
98 | const resp = await this.$postgrest.rpc('authenticate')
99 | // parsing fetch response body to json
100 | const token = await resp.json()
101 | // setting default access token globally
102 | setDefaultToken(token)
103 | }
104 | }
105 | ```
106 |
107 | ### usePostgrest(apiRoot, token)
108 |
109 | - **Type:** `Function`
110 |
111 | - **Arguments:**
112 | - `{string} apiRoot`
113 | - `{string} token`
114 |
115 | - **Returns:** `Schema`
116 |
117 | - **Usage:**
118 |
119 | Used to create a new schema for the specified baseUri with the specified default auth token. If `apiRoot` is undefined, the apiRoot of the existing Schema is used.
120 |
121 | The returned value is the same as `this.$postgrest` and can be used without the vue instance, e.g. in a store module.
122 |
123 | ### AuthError
124 |
125 | Instances of AuthError are thrown when the server rejects the authentication token.
126 |
127 | ### SchemaNotFoundError
128 |
129 | Instances of SchemaNotFoundError are thrown, when there is no valid postgrest schema at the base URI.
130 |
131 | ### FetchError
132 |
133 | Instances of FetchError are thrown on generic errors from Fetch that don't trigger the throw of more specific errors.
134 |
135 | ### PrimaryKeyError
136 |
137 | 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](./#genericmodel).
138 |
139 | ## Plugin Options
140 |
141 | Global options can be set when initializing Vue-Postgrest with `Vue.use`.
142 |
143 | ### apiRoot
144 |
145 | - **Type:** `String`
146 |
147 | - **Default:** `''`
148 |
149 | - **Details:**
150 |
151 | 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.
152 |
153 | ::: tip
154 | You can override the base URI locally by setting the [component prop](./#component-props) or [mixin option](./#apiroot-2).
155 | :::
156 |
157 | - **Example:**
158 |
159 | ``` js
160 | import VuePostgrest from 'vue-postgrest'
161 |
162 | Vue.use(VuePostgrest, {
163 | apiRoot: '/api/'
164 | })
165 | ```
166 |
167 | ### headers
168 |
169 | - **Type:** `Object`
170 |
171 | - **Default:** `{}`
172 |
173 | - **Details:**
174 |
175 | A key/value mapping of default headers to send with each request.
176 |
177 | - **Example:**
178 |
179 | ``` js
180 | import VuePostgrest from 'vue-postgrest'
181 |
182 | Vue.use(VuePostgrest, {
183 | apiRoot: '/api/',
184 | headers: {
185 | Prefer: 'timezone=' + Intl.DateTimeFormat().resolvedOptions().timeZone
186 | }
187 | })
188 | ```
189 |
190 | ## Mixin Options
191 |
192 | Mixin options are set in the component using the `pg` mixin by setting the `pgConfig` object on the component instance.
193 |
194 | ### apiRoot
195 |
196 | - **Type:** `String`
197 |
198 | - **Default:** Global [plugin option](./#plugin-options)
199 |
200 | - **Details:**
201 |
202 | 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.
203 |
204 | ::: tip
205 | This overrides the global [plugin option](./#apiroot)!
206 | :::
207 |
208 | - **Example:**
209 |
210 | ``` js
211 | import { pg } from 'vue-postgrest'
212 |
213 | export default {
214 | name: 'Component',
215 | mixins: [pg],
216 | data () {
217 | return {
218 | pgConfig: {
219 | apiRoot: '/another-api/'
220 | }
221 | }
222 | }
223 | }
224 | ```
225 |
226 | ### route
227 |
228 | - **Type:** `String`
229 |
230 | - **Details:**
231 |
232 | The table/view that is queried.
233 |
234 | - **Example:**
235 |
236 | ``` js
237 | import { pg } from 'vue-postgrest'
238 |
239 | export default {
240 | name: 'Component',
241 | mixins: [pg],
242 | data () {
243 | return {
244 | pgConfig: {
245 | route: 'clients'
246 | }
247 | }
248 | }
249 | }
250 | ```
251 |
252 | ### token
253 |
254 | - **Type:** `String`
255 |
256 | - **Default:** `undefined`
257 |
258 | - **Details:**
259 |
260 | The access token used for authorizing the connection to the API. This options sets the `Authorization` header for all requests.
261 |
262 | See also [Client Auth](https://postgrest.org/en/latest/auth.html#client-auth) in the PostgREST documentation.
263 |
264 | ::: tip
265 | You can set this globally with the [setDefaultToken method](./#setdefaulttoken-token)!
266 | :::
267 |
268 | - **Example:**
269 |
270 | ``` js
271 | import { pg } from 'vue-postgrest'
272 |
273 | export default {
274 | name: 'Component',
275 | mixins: [pg],
276 | data () {
277 | return {
278 | pgConfig: {
279 | route: 'inhabitants',
280 | token: 'YOUR_API_TOKEN'
281 | }
282 | }
283 | }
284 | }
285 | ```
286 |
287 | ### query
288 |
289 | - **Type:** `Object`
290 |
291 | - **Default:** `undefined`
292 |
293 | - **Details:**
294 |
295 | The query sent to the API is constructed from this option. See the [Query API](../query) as well as [API](https://postgrest.org/en/latest/api.html) in the PostgREST documentation for more details.
296 |
297 | - **Example:**
298 |
299 | ``` js
300 | import { pg } from 'vue-postgrest'
301 |
302 | export default {
303 | name: 'Component',
304 | mixins: [pg],
305 | data () {
306 | return {
307 | pgConfig: {
308 | route: 'inhabitants',
309 | query: {
310 | select: ['id', 'name', 'address'],
311 | and: {
312 | 'name.not.eq': 'Tion Medon',
313 | 'city.eq': 'Pau City',
314 | 'age.gt': 150
315 | }
316 | }
317 | }
318 | }
319 | }
320 | }
321 | ```
322 |
323 | ### single
324 |
325 | - **Type:** `Boolean`
326 |
327 | - **Default:** `false`
328 |
329 | - **Details:**
330 |
331 | If set to true, the request will be made with the `Accept: application/vnd.pgrst.object+json` header and `this.pg` will be of type [GenericModel](./#genericmodel). If set to false (the default), the header will be `Accept: application/json` and `this.pg` will be of type [GenericCollection](./#genericcollection).
332 |
333 | See also [Singular or Plural](https://postgrest.org/en/latest/api.html#singular-or-plural) in the PostgREST documentation.
334 |
335 | - **Example:**
336 |
337 | ``` js
338 | import { pg } from 'vue-postgrest'
339 |
340 | export default {
341 | name: 'Component',
342 | mixins: [pg],
343 | data () {
344 | return {
345 | pgConfig: {
346 | route: 'inhabitants',
347 | query: {
348 | 'id.eq': 1
349 | },
350 | single: true
351 | }
352 | }
353 | }
354 | }
355 | ```
356 |
357 | ### limit
358 |
359 | - **Type:** `Number`
360 |
361 | - **Default:** `undefined`
362 |
363 | - **Details:**
364 |
365 | Limits the count of response items by setting `Range-Unit` and `Range` headers. Only used when `single: false` is set.
366 |
367 | See also [Limits and Pagination](https://postgrest.org/en/latest/api.html#limits-and-pagination) in the PostgREST documentation.
368 |
369 | - **Example:**
370 |
371 | ``` js
372 | import { pg } from 'vue-postgrest'
373 |
374 | export default {
375 | name: 'Component',
376 | mixins: [pg],
377 | data () {
378 | return {
379 | pgConfig: {
380 | route: 'inhabitants',
381 | query: {
382 | 'age.gt': 150
383 | },
384 | // get the first 10 inhabitants that pass the filter query
385 | limit: 10
386 | }
387 | }
388 | }
389 | }
390 | ```
391 |
392 |
393 | ### offset
394 |
395 | - **Type:** `Number`
396 |
397 | - **Default:** `undefined`
398 |
399 | - **Details:**
400 |
401 | Offset the response items, useful e.g. for pagination, by setting `Range-Unit` and `Range` headers. Only used when `single: false` is set.
402 |
403 | See also [Limits and Pagination](https://postgrest.org/en/latest/api.html#limits-and-pagination) in the PostgREST documentation.
404 |
405 | - **Example:**
406 |
407 | ``` js
408 | import { pg } from 'vue-postgrest'
409 |
410 | export default {
411 | name: 'Component',
412 | mixins: [pg],
413 | data () {
414 | return {
415 | pgConfig: {
416 | route: 'inhabitants',
417 | query: {
418 | 'age.gt': 150
419 | },
420 | // get all inhabitants that pass the filter query, starting from no. 5
421 | offset: 5
422 | }
423 | }
424 | }
425 | }
426 | ```
427 |
428 | ### count
429 |
430 | - **Type:** `String`
431 |
432 | - **Default:** `undefined`
433 |
434 | - **Options:**
435 |
436 | - `exact`
437 | - `planned`
438 | - `estimated`
439 |
440 | - **Details:**
441 |
442 | Only used when `single: false` is set.
443 |
444 | See PostgREST docs for details on those options:
445 |
446 | - [Exact Count](https://postgrest.org/en/latest/api.html#exact-count)
447 | - [Planned Count](https://postgrest.org/en/latest/api.html#planned-count)
448 | - [Estimated Count](https://postgrest.org/en/latest/api.html#estimated-count)
449 |
450 | - **Example:**
451 |
452 | ``` js
453 | import { pg } from 'vue-postgrest'
454 |
455 | export default {
456 | name: 'Component',
457 | mixins: [pg],
458 | data () {
459 | return {
460 | pgConfig: {
461 | route: 'inhabitants',
462 | query: {
463 | 'age.gt': 150
464 | },
465 | count: 'exact'
466 | }
467 | }
468 | }
469 | }
470 | ```
471 |
472 | ## Mixin Hooks
473 |
474 | Hooks are called on the component instance that uses the `pg` mixin.
475 |
476 | ### onError
477 |
478 | - **Type:** `Function`
479 |
480 | - **Arguments:**
481 |
482 | - `{FetchError | AuthError} error`
483 |
484 | - **Details:**
485 |
486 | Called when a FetchError or AuthError occurs. The Hook gets passed the error object.
487 |
488 | - **Example:**
489 |
490 | ``` js
491 | import { pg } from 'vue-postgrest'
492 |
493 | export default {
494 | name: 'Component',
495 | mixins: [pg],
496 | data () {
497 | return {
498 | pgConfig: {
499 | route: 'inhabitants',
500 | query: {}
501 | }
502 | }
503 | },
504 | onError (err) {
505 | // an error occured!
506 | console.log(err)
507 | }
508 | }
509 | ```
510 |
511 | ## Mixin Properties
512 |
513 | Using the `pg` mixin exposes `this.pg` with the following properties.
514 |
515 | ### pg
516 |
517 | - **Type:** `GenericCollection | GenericModel`
518 |
519 | - **Details:**
520 |
521 | Dependent on the `pgConfig.single` setting this is either of type [GenericCollection](./#genericcollection) or [GenericModel](./#genericmodel). A GenericCollection is essentially just an Array of GenericModels with some additional methods. Both types have a `pg.$get()` method available to manually refresh the request.
522 |
523 | - **Example:**
524 |
525 | ``` js
526 | import { pg } from 'vue-postgrest'
527 |
528 | export default {
529 | name: 'Component',
530 | mixins: [pg],
531 | data () {
532 | return {
533 | pgConfig: {
534 | route: 'inhabitants',
535 | query: {}
536 | }
537 | }
538 | },
539 | computed: {
540 | inhabitants () {
541 | return this.pg
542 | }
543 | }
544 | }
545 | ```
546 |
547 | ## Instance Methods
548 |
549 | The instance method `vm.$postgrest` is available on your Vue Instance after installing the plugin.
550 |
551 | ### $postgrest
552 |
553 | - **Type:** `Route`
554 |
555 | - **Arguments:**
556 |
557 | - `{string} apiRoot`
558 |
559 | - `{string} token`
560 |
561 | - **Returns:** `Schema`
562 |
563 | - **Throws:** `SchemaNotFoundError`
564 |
565 | - **Usage:**
566 |
567 | Used to create a new schema for the specified baseUri with the specified default auth token. If `apiRoot` is undefined, the apiRoot of the existing Schema is used.
568 |
569 | ### $postgrest[route]
570 |
571 | - **Type:** `Route`
572 |
573 | - **Throws:** `AuthError | FetchError`
574 |
575 | - **Usage:**
576 |
577 | After the schema is [ready](./#postgrest-ready), all available routes are exposed on the $postgrest instance.
578 | The exposed `Route` accepts the following arguments:
579 |
580 | - `{string} method` one of `'OPTIONS'`, `'GET'`, `'HEAD'`, `'POST'`, `'PATCH'`, `'PUT'` or `'DELETE'`
581 |
582 | - `{object} query` see [Query](../query)
583 |
584 | - `{object} options` additional options, see below
585 |
586 | - `{object} body` payload for post/patch/put requests
587 |
588 | Available options are:
589 |
590 | - `{string} accept` `Accept` header to set or one of the options 'single', 'binary' or 'text', which set the header automatically. Default header is 'application/json'.
591 |
592 | - `{number} limit` Limit the response to no. of items by setting the `Range` and `Range-Unit` headers
593 |
594 | - `{number} offset` Offset the response by no. of items by setting the `Range` and `Range-Unit` headers
595 |
596 | - `{string} return` Set `return=[value]` part of `Prefer` header
597 |
598 | - `{string} params` Set `params=[value]` part of `Prefer` header
599 |
600 | - `{string} count` Set `count=[value]` part of `Prefer` header
601 |
602 | - `{string} resolution` Set `resolution=[value]` part of `Prefer` header
603 |
604 | - `{object} headers` Overwrite headers. Keys are header field names, values are strings.
605 |
606 | The `Route` instance provides convencience methods for calling the following HTTP requests directly, omit the `method` argument in this case:
607 |
608 | - `$postgrest.route.options([query, options])`
609 |
610 | - `$postgrest[route].get([query, options])`
611 |
612 | - `$postgrest[route].head([query, options])`
613 |
614 | - `$postgrest[route].post([query, options, body])`
615 |
616 | - `$postgrest[route].patch([query, options, body])`
617 |
618 | - `$postgrest[route].put([query, options, body])`
619 |
620 | - `$postgrest[route].delete([query, options])`
621 |
622 | - **Example:**
623 |
624 | ``` js
625 | export default {
626 | name: 'Galaxy',
627 | data () {
628 | return {
629 | planets: undefined,
630 | cities: undefined
631 | }
632 | }
633 | async mounted: {
634 | // wait for the schema to be ready
635 | await this.$postgrest.$ready
636 | const planetsResp = await this.$postgrest.planets('GET')
637 | const citiesResp = await this.$postgrest.cities.get()
638 | this.planets = await planetsResp.json()
639 | this.cities = await citiesResp.json()
640 | }
641 | }
642 | ```
643 |
644 | ### $postgrest.$ready
645 |
646 | - **Type:** `Promise`
647 |
648 | - **Throws:** `SchemaNotFoundError`
649 |
650 | - **Usage:**
651 |
652 | The promise resolves, when the schema was successfully loaded and rejects if no valid schema was found.
653 |
654 | ::: tip
655 | This can also be called on a [route](./#postgrest-route) or a [rpc](./#postgrest-rpc).
656 | :::
657 |
658 | - **Example:**
659 |
660 | ``` js
661 | export default {
662 | name: 'Component',
663 | async mounted: {
664 | // wait for the schema to be ready
665 | try {
666 | await this.$postgrest.$ready
667 | } catch (e) {
668 | console.log('Could not connect to API...')
669 | }
670 | }
671 | }
672 | ```
673 |
674 | ### $postgrest.$route(route)
675 |
676 | - **Type:** `Function`
677 |
678 | - **Arguments:**
679 |
680 | - `{string} route`
681 |
682 | - **Returns:** `Route`
683 |
684 | - **Usage:**
685 |
686 | 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 `Route` for the specified route.
687 |
688 | - **Example:**
689 |
690 | ``` js
691 | export default {
692 | name: 'Cities',
693 | methods: {
694 | async getCities () {
695 | return this.$postgrest.$route('cities').get()
696 | },
697 | async addCity () {
698 | await this.$postgrest.$route('cities').post({}, {}, { name: 'Galactic City' })
699 | }
700 | }
701 | }
702 | ```
703 |
704 | - **See also:** [$postgrest[route]](./#postgrest-route)
705 |
706 | ### $postgrest.rpc[function-name]
707 |
708 | - **Type:** `RPC`
709 |
710 | - **Usage:**
711 |
712 | After the schema is [ready](./#postgrest-ready), all available stored procedures are exposed on $postgrest.rpc[function-name] and can be called like this: `$postgrest.rpc[function-name]([params, options])`.
713 |
714 | The `params` object contains parameters that are passed to the stored procedure.
715 |
716 | Available `options` are:
717 |
718 | - `{boolean} get` set request method to 'GET' if true, otherwise 'POST'
719 |
720 | - `{string} accept` `Accept` header to set or one of the options 'single', 'binary' or 'text', which set the header automatically. Default header is 'application/json'.
721 |
722 | - `{object} headers` Properties of this object overwrite the specified header fields of the request.
723 |
724 | - **Example:**
725 |
726 | ``` js
727 | export default {
728 | name: 'Component',
729 | methods: {
730 | async destroyAllPlanets () {
731 | // wait till schema is loaded
732 | await this.$postgrest.$ready
733 | const result = await this.$postgrest.rpc.destroyplanets({ countdown: false }, {
734 | accept: 'text',
735 | headers: { 'Warning': 'Will cause problems!' }
736 | })
737 |
738 | if (await result.text() !== 'all gone!') {
739 | this.$postgrest.rpc.destroyplanets({ force: true })
740 | }
741 | }
742 | }
743 | }
744 | ```
745 |
746 | ### $postgrest.rpc(function-name[, params, options])
747 |
748 | - **Type:** `Function`
749 |
750 | - **Throws:** `AuthError | FetchError`
751 |
752 | - **Arguments:**
753 |
754 | - `{string} function-name`
755 |
756 | - `{object} params`
757 |
758 | - `{object} options`
759 |
760 | - **Returns:** API response
761 |
762 | - **Usage:**
763 |
764 | Calls a stored procedure on the API. `function-name` specifies the stored procedure to call. For `params` and `options` see [$postgrest.rpc](./#postgrest-rpc)
765 |
766 | - **Example:**
767 |
768 | ``` js
769 | export default {
770 | name: 'Component',
771 | methods: {
772 | async destroyAllPlanets () {
773 | await this.$postgrest.rpc('destroyplanets', { countdown: false }, {
774 | accept: 'text',
775 | headers: { 'Warning': 'Will cause problems!' }
776 | })
777 | }
778 | }
779 | }
780 | ```
781 |
782 | ## Component Props
783 |
784 | The `` component accepts all [mixin options](./#mixin-options) as props, see above for details.
785 |
786 | - **Example**:
787 |
788 | ``` html
789 |
790 |
795 |
796 | ```
797 |
798 | ## Component Slot Scope
799 |
800 | The `` component provides the `pg` [mixin property](./#mixin-properties) as scope in the default slot, see above for details.
801 |
802 | - **Example**:
803 |
804 | ``` html
805 |
806 |
809 |
810 |
811 |