Modules

CozyClient
AppCollection
CozyStackClient
DocumentCollection

Abstracts a collection of documents of the same doctype, providing CRUD methods and other helpers.

FileCollection

Abstracts a collection of files

Files are a special type of documents and are handled differently by the stack: special routes are to be used, and there is a notion of referenced files, aka files associated to a specific document

OAuthClient
PermissionCollection

Interact with permissions

SharingCollection

Interact with sharing doctypes

Constants

encode

Encode an object as querystring, values are encoded as URI components, keys are not.

buildURL

Returns a URL from base url and a query parameter object. Any undefined parameter is removed.

Functions

normalizeDoctypeSchema()

Returns a normalized schema object from the schema definition.

  • Relationships are resolved to classes if needed
  • The name of the relationship (its key in the schema definition) is included in the relationship
  • Empty relationships are nulled
getDoctypeSchema()

Returns the schema for a doctype

getRelationship()

Returns the relationship for a given doctype/name

validate()

Validates a document considering the descriptions in schema.attributes.

withClient(Component)function

HOC to provide client from context as prop

queryConnect(querySpecs)function

HOC creator to connect component to several queries in a declarative manner

startReplication()void

User of the link can call this to start ongoing replications. Typically, it can be used when the application regains focus.

stopReplication()void

User of the link can call this to stop ongoing replications. Typically, it can be used when the applications loses focus.

startReplicationLoop()

Starts periodic syncing of the pouches

stopReplicationLoop()

Stop periodic syncing of the pouches

replicateOnce()

Starts replication

defaultSelector(options)Array

Compute fields that should be indexed for a mango query to work

setIntervalPromise()

Will periodically run a function so that when the promise is resolved, the next function is called after ms.

Returns a function which cancels the periodic calling. When canceled, if there is an ongoing promise, it will continue.

uri()

Template tag function for URIs encoding

Will automatically apply encodeURIComponent to template literal placeholders

attempt()

Helps to avoid nested try/catch when using async/await

Inspired by a Go pattern: http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/

sleep()

Helps to avoid nested try/catch when using async/await — see documentation for attemp

CozyClient

cozyClient.collection(doctype) ⇒ DocumentCollection

Forwards to a stack client instance and returns a DocumentCollection instance.

Kind: instance method of CozyClient

Param Type Description
doctype String The collection doctype.

cozyClient.getDocumentSavePlan(document, relationships) ⇒ Array.<object>

getDocumentSavePlan - Creates a list of mutations to execute to create a document and its relationships.

Kind: instance method of CozyClient
Returns: Array.<object> - One or more mutation to execute

Param Type Description
document object The base document to create
relationships object The list of relationships to add, as a dictionnary. Keys should be relationship names and values the documents to link.

Example

const baseDoc = { _type: 'io.cozy.todo', label: 'Go hiking' }
// relations can be arrays or single objects
const relationships = {
  attachments: [{ _id: 12345, _type: 'io.cozy.files' }, { _id: 6789, _type: 'io.cozy.files' }],
  bills: { _id: 9999, _type: 'io.cozy.bills' }
}
client.getDocumentSavePlan(baseDoc, relationships)

cozyClient.hydrateDocument()

Instantiate relationships on a document

The original document is kept in the target attribute of the relationship

Kind: instance method of CozyClient

cozyClient.register(cozyURL) ⇒ object

Performs a complete OAuth flow using a Cordova webview for auth. The register method’s name has been chosen for compat reasons with the Authentication compo.

Kind: instance method of CozyClient
Returns: object - Contains the fetched token and the client information.

Param Type Description
cozyURL string Receives the URL of the cozy instance.

cozyClient.startOAuthFlow(openURLCallback) ⇒ object

Performs a complete OAuth flow, including upating the internal token at the end.

Kind: instance method of CozyClient
Returns: object - Contains the fetched token and the client information. These should be stored and used to restore the client.

Param Type Description
openURLCallback function Receives the URL to present to the user as a parameter, and should return a promise that resolves with the URL the user was redirected to after accepting the permissions.

cozyClient.renewAuthorization() ⇒ object

Renews the token if, for instance, new permissions are required.

Kind: instance method of CozyClient
Returns: object - Contains the fetched token and the client information.

cozyClient.setData(data)

Directly set the data in the store, without using a query This is useful for cases like Pouch replication, which wants to set some data in the store.

Kind: instance method of CozyClient

Param Type Description
data Object

AppCollection

appCollection.all() ⇒ Object

Lists all apps, without filters.

The returned documents are not paginated by the stack.

Kind: instance method of AppCollection
Returns: Object - The JSON API conformant response.
Throws:

CozyStackClient

cozyStackClient.collection(doctype) ⇒ DocumentCollection

Creates a DocumentCollection instance.

Kind: instance method of CozyStackClient

Param Type Description
doctype String The collection doctype.

cozyStackClient.fetch(method, path, body, options) ⇒ Object

Fetches JSON in an authorized way.

Kind: instance method of CozyStackClient
Throws:

Param Type Description
method String The HTTP method.
path String The URI.
body Object The payload.
options Object

DocumentCollection

Abstracts a collection of documents of the same doctype, providing CRUD methods and other helpers.

documentCollection.all(options) ⇒ Object

Lists all documents of the collection, without filters.

The returned documents are paginated by the stack.

Kind: instance method of DocumentCollection
Returns: Object - The JSON API conformant response.
Throws:

Param Type Description
options Object The fetch options: pagination & fetch of specific docs.

documentCollection.find(selector, options) ⇒ Object

Returns a filtered list of documents using a Mango selector.

The returned documents are paginated by the stack.

Kind: instance method of DocumentCollection
Returns: Object - The JSON API conformant response.
Throws:

Param Type Description
selector Object The Mango selector.
options Object The query options.

documentCollection.getIndexFields(options) ⇒ Array

Compute fields that should be indexed for a mango query to work

Kind: instance method of DocumentCollection
Returns: Array - - Fields to index

Param Type Description
options Object Mango query options

FileCollection

Abstracts a collection of files

Files are a special type of documents and are handled differently by the stack: special routes are to be used, and there is a notion of referenced files, aka files associated to a specific document

fileCollection.find(selector, options) ⇒ Object

Returns a filtered list of documents using a Mango selector.

The returned documents are paginated by the stack.

Kind: instance method of FileCollection
Returns: Object - The JSON API conformant response.
Throws:

Param Type Description
selector Object The Mango selector.
options Object The query options.

fileCollection.findReferencedBy(document, {, limit) ⇒ object

async findReferencedBy - Returns the list of files referenced by a document — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/

Kind: instance method of FileCollection
Returns: object - The JSON API conformant response.

Param Type Description
document object A JSON representing a document, with at least a _type and _id field.
{ number skip = 0 For pagination, the number of referenced files to skip
limit number } For pagination, the number of results to return.

OAuthClient

oAuthClient.register() ⇒ promise

Registers the currenly configured client with the OAuth server.

Kind: instance method of OAuthClient
Returns: promise - A promise that resolves with a complete list of client information, including client ID and client secret.
Throws:

oAuthClient.unregister() ⇒ promise

Unregisters the currenly configured client with the OAuth server.

Kind: instance method of OAuthClient
Throws:

oAuthClient.fetchInformation() ⇒ promise

Fetches the complete set of client information from the server after it has been registered.

Kind: instance method of OAuthClient
Throws:

oAuthClient.updateInformation(information, resetSecret) ⇒ promise

Overwrites the client own information. This method will update both the local information and the remote information on the OAuth server.

Kind: instance method of OAuthClient
Returns: promise - A promise that resolves to a complete, updated list of client information
Throws:

Param Type Default Description
information object Set of information to update. Note that some fields such as clientID can’t be updated.
resetSecret boolean false = false Optionnal, whether to reset the client secret or not

oAuthClient.generateStateCode() ⇒ string

Generates a random state code to be used during the OAuth process

Kind: instance method of OAuthClient

oAuthClient.getAuthCodeURL(stateCode, scopes) ⇒ string

Generates the URL that the user should be sent to in order to accept the app’s permissions.

Kind: instance method of OAuthClient
Returns: string - The URL
Throws:

Param Type Description
stateCode string A random code to be included in the URl for security. Can be generated with client.generateStateCode()
scopes Array = [] An array of permission scopes for the token.

oAuthClient.getAccessCodeFromURL(pageURL, stateCode) ⇒ string

Retrieves the access code contained in the URL to which the user is redirected after accepting the app’s permissions (the redirectURI).

Kind: instance method of OAuthClient
Returns: string - The access code
Throws:

Param Type Description
pageURL string The redirected page URL, containing the state code and the access code
stateCode string The state code that was contained in the original URL the user was sent to (see client.getAuthCodeURL())

oAuthClient.fetchAccessToken(accessCode) ⇒ Promise

Exchanges an access code for an access token. This function does not update the client’s token.

Kind: instance method of OAuthClient
Returns: Promise - A promise that resolves with an AccessToken object.
Throws:

Param Type Description
accessCode string The access code contained in the redirection URL — sett client.getAccessCodeFromURL()

oAuthClient.refreshToken() ⇒ Promise

Retrieves a new access token by refreshing the currently used token.

Kind: instance method of OAuthClient
Returns: Promise - A promise that resolves with a new AccessToen object
Throws:

oAuthClient.setCredentials(token)

Updates the client’s stored token

Kind: instance method of OAuthClient

Param Type Description
token string = null The new token to use — can be a string, a json object or an AccessToken instance.

oAuthClient.setOAuthOptions(options)

Updates the OAuth informations

Kind: instance method of OAuthClient

Param Type Description
options object Map of OAuth options

PermissionCollection

Interact with permissions

permissionCollection.getOwnPermissions() ⇒ object

async getOwnPermissions - Gets the permission for the current token

Kind: instance method of PermissionCollection

SharingCollection

Interact with sharing doctypes

sharingCollection.share(document, recipients, sharingType, description, [previewPath])

share - Creates a new sharing. See https://docs.cozy.io/en/cozy-stack/sharing/#post-sharings

Kind: instance method of SharingCollection

Param Type Default Description
document object The document to share. Should have and _id and a name.
recipients array A list of io.cozy.contacts
sharingType string
description string
[previewPath] string null Relative URL of the sharings preview page

sharingCollection.getDiscoveryLink(sharingId, sharecode) ⇒ string

getDiscoveryLink - Returns the URL of the page that can be used to accept a sharing. See https://docs.cozy.io/en/cozy-stack/sharing/#get-sharingssharing-iddiscovery

Kind: instance method of SharingCollection

Param Type
sharingId string
sharecode string

encode

Encode an object as querystring, values are encoded as URI components, keys are not.

Kind: global constant

buildURL

Returns a URL from base url and a query parameter object. Any undefined parameter is removed.

Kind: global constant

normalizeDoctypeSchema()

Returns a normalized schema object from the schema definition.

Kind: global function

getDoctypeSchema()

Returns the schema for a doctype

Kind: global function

getRelationship()

Returns the relationship for a given doctype/name

Kind: global function

validate()

Validates a document considering the descriptions in schema.attributes.

Kind: global function

withClient(Component) ⇒ function

HOC to provide client from context as prop

Kind: global function
Returns: function - - Component that will receive client as prop

Param Type Description
Component Component wrapped component

queryConnect(querySpecs) ⇒ function

HOC creator to connect component to several queries in a declarative manner

Kind: global function
Returns: function - - HOC to apply to a component

Param Type Description
querySpecs object Definition of the queries

startReplication() ⇒ void

User of the link can call this to start ongoing replications. Typically, it can be used when the application regains focus.

Kind: global function
Access: public

stopReplication() ⇒ void

User of the link can call this to stop ongoing replications. Typically, it can be used when the applications loses focus.

Kind: global function
Access: public

startReplicationLoop()

Starts periodic syncing of the pouches

Kind: global function

stopReplicationLoop()

Stop periodic syncing of the pouches

Kind: global function

replicateOnce()

Starts replication

Kind: global function

defaultSelector(options) ⇒ Array

Compute fields that should be indexed for a mango query to work

Kind: global function
Returns: Array - - Fields to index

Param Type Description
options Object Mango query options

setIntervalPromise()

Will periodically run a function so that when the promise is resolved, the next function is called after ms.

Returns a function which cancels the periodic calling. When canceled, if there is an ongoing promise, it will continue.

Kind: global function

uri()

Template tag function for URIs encoding

Will automatically apply encodeURIComponent to template literal placeholders

Kind: global function
Example

const safe = uri`/data/${doctype}/_all_docs?limit=${limit}`

attempt()

Helps to avoid nested try/catch when using async/await

Inspired by a Go pattern: http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/

Kind: global function
Example

if (await attempt(collection.all()) return
await sleep(1000)
if (await attempt(collection.all()) return
await sleep(1000)
return

sleep()

Helps to avoid nested try/catch when using async/await — see documentation for attemp

Kind: global function