📘 This section describes methods for working with the Appery.io database.
Initialization
$a.db helper works with Appery.io Database specified in databaseId property of Settings service. But you can set/change database at any time with setDatabaseId method.
Settings service
This is a common Settings file (Create New -> Service -> Settings (REST settings)). Available settings are:
Property | Value | Description |
---|---|---|
databaseId | 65733fc90a975a0123456789 | Database API Key |
addHeaders
addHeaders(headers: {[key:string]: string}): void
Add headers to default list of headers.
Parameters
Parameters | Description | Required |
---|---|---|
headers | Object with new headers | Yes. |
Example
this.$a.db.addHeaders({
"Content-Type": "application/json"
});
autoLogin
autoLogin(): Promise
Login with previously saved credentials (see Login section for details).
Returns
Promise with user data or null
if login fails.
Example
let user = this.$a.db.autoLogin();
if (!user) {
console.log("autologin fails");
}
clearItem
clearItem(item): void
Remove from item _id, acl, _createdAt, _updatedAt properties.
Example
item = this.$a.db.clearItem(item);
deleteFile
deleteFile(fileName: string, options): Promise
Remove from Database file with specified fileName
Parameters
- fileName- name of the file to be deleted;
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error;
Example
await this.$a.db.deleteFile("75be9370-4313-43ea-bebd-3416decdbe14.test.png");
getById
getById(collection: string, id: string, options?): Promise
Get item from collection by id.
Parameters
- collection - name of the collection;
- id - item id;
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error;
- cache - take result from cache if possible;
- saveInCache - save result to cache.
Returns
Promise with received object
Example
let item = await this.$a.db.getById("tasks", "52c6bfa7e4b03c65ed01f039");
getDatabaseId
getDatabaseId(): string|undefined
Get current Database Id.
Returns
Current Database Id or undefined if Database Id was not set.
Example
let dbId = this.$a.db.getDatabaseId();
getDefaultParams
getDefaultParams(): Object|null
Get default parameters.
Returns
Object with default parameters of null.
Example
let params = this.$a.db.getDefaultParams();
getFileUrl
getFileUrl(fileName: string): string
Get direct link to the specified file.
Parameters
- fileName - name of the file;
Returns
String - direct link to the file.
Example
let url = this.$a.db.getFileUrl("75be9370-4313-43ea-bebd-3416decdbe14.test.png");
getHeaders
getHeaders(options?: {headers: any, clearContentType?: boolean, noExtend?: boolean}): {headers: HttpHeaders}
Get current headers as HttpHeaders.
Parameters
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used.
getSessionToken
getSessionToken(): string|undefined
Get current Session Token.
Returns
Current Session Token or undefined if Session Token was not set.
Example
let token = this.$a.db.getSessionToken();
login
login(payload: {username: string, password: string, rememberMe?: boolean} , options?): Promise
Login with provided credentials. If login succeed then sessionToken will be set to X-Appery-Session-Token header.
Parameters
- payload - user's credentials:
- username - login;
- password - password;
- rememberMe - (optional). If true - user's credentials will be saved in secure storage (secure Storage only works in native applications (apk/aab, ipa)). This saved credentials will be used by autoLogin method;
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error.
Returns
Promise with user data or null
if login fails.
Example
let userData = await this.$a.db.login(
{
username: "Joe",
password: "123",
rememberMe: true
}
);
logout
logout(): Promise
Logout user. If the user's credentials were saved in secure storage, they will be cleared.
Example
await this.$a.db.logout();
query
query(collection: string, params?: QueryParams, options?): Promise<any[]>
Query collection.
Parameters
- collection - name of the collection;
- params - query params object. See details. Available params are:
- where - (optional). object;
- count - (optional). number;
- include - (optional). string;
- sort - (optional). string;
- limit - (optional). number;
- skip - (optional). number;
- proj - (optional). object;
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error;
- cache - take result from cache if possible;
- saveInCache - save result to cache.
Returns
Promise with array of received objects
Example
let items = await this.$a.db.query("tasks", {where: {"status": "done"}});
queryOne
queryOne(collection: string, params?: QueryParams, options?): Promise<any[]>
Query collection.
Parameters
- collection - name of the collection;
- params - query params object. See details. Available params are:
- where - (optional). object;
- count - (optional). number;
- include - (optional). string;
- sort - (optional). string;
- skip - (optional). number;
- proj - (optional). object;
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error;
- cache - take result from cache if possible;
- saveInCache - save result to cache.
Returns
Promise with received object or undefined if nothing was found
Example
let item = await this.$a.db.queryOne("tasks", {where: {"status": "done"}});
remove
remove(collection: string, item, options?): Promise
Remove item from Database.
Parameters
- collection - name of the collection;
- item - string (item's _id), item object or array of item objects to be removed from the collection. Actually only _id property in the item object is needed;
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error;
Returns
If item parameter is a single item then Promise with an empty object will be returned.
If item parameter is an array of items then Promise with results array for each item will be returned. For example:
[
{
"success": {}
},
{
"error": {
"code": "DBSD205",
"description": "Collection 'tasks' doesn't contain object with id 65379e1190fedb4582222222."
}
}
]
Example
await this.$a.db.remove("tasks", "52c6bfa7e4b03c65ed01f039");
removeWithFile
removeWithFile(collection: string, item, filePropName: string, options?): Promise
Remove item from Database with linked to the item file
Parameters
- collection - name of the collection;
- item - (object) item to be removed from the collection;
- filePropName - name of the property in the collection with file reference;
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error;
Example
await this.$a.db.removeWithFile("tasks", item, "imageFile");
save
save(collection: string, item, options?): Promise
Save item to Database.
Parameters
- collection - name of the collection;
- item - item or array of items to be saved
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error.
Returns
If item parameter is a single item then Promise with the saved object will be returned.
If item parameter is an array of items then Promise with results array for each item will be returned. For example:
[
{
"success": {
"_id": "65379e1190fedb4581111111",
"_createdAt": "2023-10-24T10:36:01.930Z"
}
},
{
"success": {
"_updatedAt": "2023-10-24T10:34:53.937Z"
}
},
{
"error": {
"code": "DBSU205",
"description": "Collection 'tasks' doesn't contain object with id 65379e1190fedb4582222222."
}
}
]
Example
let newItem = {name: "Buy milk", description: "Buy one bottle", status: "new"};
let item = this.$a.db.save("tasks", newItem);
saveWithFile
saveWithFile(collection: string, item, fileData?: {base64Data?: string, fileName?: string, filePropName?: string}, options?): Promise
Save item with linked file to Database.
Parameters
- collection - name of the collection;
- item - item to be saved
- fileData - (optional) file data:
- base64Data - (optional) base64Data or dataURL.
- fileName - (optional) name of the new file. Default is "file.dat"
- filePropName - (optional) name of the property in the collection with file reference. Default is "file"
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error;
- deleteOldFile - boolean. Delete old file if it exists or not (default is false).
Returns
Promise with the saved object
Example
let newItem = {name: "Buy milk", description: "Buy one bottle", status: "new"};
let imageDataURL = "data:image/gif;base64,R0lGO\
DdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt\
3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvON\
mOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUq\
rXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxy\
endzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZX\
ZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4\
OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lE\
ewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5V\
WzXyym7PHhhx4dbgYKAAA7";
let item = this.$a.db.saveWithFile(
"tasks",
newItem,
{
base64Data: imageDataURL,
filePropName: "imageFile"
});
setDatabaseId
setDatabaseId(databaseId?: string|null|undefined): void
Set X-Appery-Database-Id header.
By default database Id is set to the value set in "Settings" -> "databaseId" config.
Parameters
- databaseId - database Id.
Example
this.$a.db.setDatabaseId("51b8c9a7e4b0e832dd012345");
setDefaultParams
setDefaultParams(params?: {[key:string]: string}|null|undefined): void
Set default parameters.
Parameters
- params - (optional) object|null|undefined. Default parameters are not updated. The passed object is saved as-is as the default parameters. If params is not provided (or null|undefined), the default parameters are cleared.
Example
this.$a.db.setDefaultParams({
"limit": "1500",
"sort": "studentName"
});
setHeaders
setHeaders(headers: {[key:string]: string}): void
Set default list of headers.
Parameters
- headers - object with headers. Default list of headers is not updated. The passed object is saved as-is as the default list of headers.
Example
this.$a.db.setHeaders({
"Content-Type": "application/json"
});
setSessionToken
setSessionToken(sessionToken?: string|null|undefined): void
Set X-Appery-Session-Token header. If you login with login or userCreate then session token will be set automatically and there is no need to set session token with this method.
Parameters
- sessionToken - string with new token or null|undefined if you want to remove token header.
Example
let url = this.$a.db.setSessionToken("86a3f366-ec22-4006-9571-05b49965aef2");
uploadBase64File
uploadBase64File(base64Data: string, fileName?: string, options?): Promise<{fileName:string, originalFileName:string, fileurl:string}|null>
Save item with linked file to Database.
Parameters
- base64Data - (optional) base64Data or dataURL.
- fileName - (optional) name of the new file. Default is "file.dat"
Returns
Promise with the saved file data {fileName:string, originalFileName:string, fileurl:string}
Example
let imageDataURL = "data:image/gif;base64,R0lGO\
DdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt\
3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvON\
mOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUq\
rXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxy\
endzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZX\
ZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4\
OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lE\
ewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5V\
WzXyym7PHhhx4dbgYKAAA7";
let file = this.$a.db.uploadBase64File(imageDataURL);
userCreate
userCreate(userData, options?): Promise
Create new User. Under the hood, after creation, the new user will be automatically logged in.
Parameters
- userData - object with user's data. Required fields: username and password.
- options - (optional). Available options are:
- headers - object with new headers;
- clearContentType - boolean. If true - 'Content-Type' header will be deleted;
- noExtend - boolean. If true - default headers will not be extended and only headers from options will be used;
- loadingStart - show loading on service execution start (default is false);
- loadingEnd - hide loading on service execution end (default is false);
- loading - boolean. Shortening for (
loadingStart = true
andloadingEnd = true
); - showError - show toast with error if error occurs (default is true);
- message - message to be shown after success service execution;
- errorMessage - message to be shown after error in service execution;
- throwError - throw error if service execution ends with error.
Returns
Promise with the saved user's data.
Example
await this.$a.db.userCreate({
"username": "[email protected]",
"password": "123",
"status": "unconfirmed"
});
userGetData
userGetData(options?): Promise
Get current user's data.
Parameters
- options - (optional). See available options in userCreate
Returns
Promise with the full user's data.
Example
let userData = await this.$a.db.userGetData();
userUpdate
userUpdate(userData, options?): Promise
Update current user's data.
Parameters
- userData - object with user's data to be updated.
- options - (optional). See available options in userCreate
Returns
Promise with the full user's data.
Example
await this.$a.db.userUpdate({
"status": "active"
});
userRemove
userRemove(options?): Promise
Remove current user.
Parameters
- options - (optional). See available options in userCreate
Returns
Promise
Example
await this.$a.db.userRemove();
userGetId
userGetId(): string
Get current user's id.
Returns
String. Current user id.
Example
let userId = this.$a.db.userGetId();
userSetId
userSetId(userId?: string|null|undefined): void;
Set current user's id. If you login with login or userCreate then user ID will be set automatically and there is no need to set user ID with this method.
Parameters
- userId- (optional). User ID
Example
this.$a.db.userSetId("653790ab3c62ea7f21111111");