@viewar/backend-api
Package to allow apps to change ViewAR content in the backend.
Usage
Each request (read or write) will return the changed data from the server.
This way the programmer can keep his own state in sync with the server state.
Configuration
First a user must configure this module to get access to the backend. This should be done before any call to this API:
import { Configuration } from '@viewar/backend-api';
Configuration.setHost('https://dev2.viewar.com');
Authentication
Second a user has to authenticate to set a valid token. The package internally saves the token during runtime.
One way is to authenticate with email and password:
import { Authentication } from '@viewar/backend-api';
const token = await Authentication.authenticate('john@viewar.com', '12345');
The other way is to directly use the token:
import { Authentication } from '@viewar/backend-api';
const token = 'token1234';
Authentication.useToken(token);
Storage
The storage is to read from ViewAR's cloud storage or write into it.
import { Storage } from '@viewar/backend-api';
const storageId = 'viewar.app.id';
content = await Storage.write(storageId, 'test.json', {
test: 1234,
});
let content = await Storage.read(storageId, 'test.json');
Resources
The resources namespace is used to handle resources on the ViewAR servers.
import { Resources } from '@viewar/backend-api';
const file = new File(['mocked file content'], 'filename.txt');
const name = 'Test Texture';
const type = 'png';
const texture = await Resources.createTexture(file, name, type);
ModelData
ModelData is to read or write to a model's data field.
import { ModelData } from '@viewar/backend-api';
const modelId = '108721';
let data = await ModelData.get(modelId);
data = await ModelData.save(
modelId,
Object.assign({}, data, {
test: 2345,
})
);
Error Handling
Every backend request can throw an error. If the request fails to reach the server a RequestError is thrown.
If there is an error in the server response (e.g. authentication error) a BackendError is thrown.
import { Backend, ModelData, Authentication } from "@viewar/backend-api";
const token = "invalid token";
const modelId = "108721";
Authentication.useToken(token);
try {
await ModelData.get(modelId);
} catch(err) {
if (err instanceOf Backend.RequestError) {
console.log("Failed to reach the server!", err.message);
} else if (err instanceOf Backend.BackendError) {
console.log("Server returned an error in response", err.message);
}
} else if (err instanceOf Backend.InvalidTokenError) {
console.log("Please authenticate first.", err.message);
}
}