@appstrax/services
v0.6.1
Published
The Appstrax javascript npm library
Readme
@appstrax/services
Table of Contents
- Overview
- Getting Started
- Installation
- Setup
- Auth Service
- User Service
- Database Service
- Database Error Messages
- Storage Service
Overview
Appstrax in partnership with CodeCapsules provides software tools and infrastructure to assist in the development, hosting and managing of your applications.
Getting Started
To use the Appstrax Services, an instance of the API is required. Each API instance has an admin panel which allows admin users to manage registered users, application data and uploaded files and application configuration accordingly.
To get this instance set-up, please send an email to [email protected] and we'll help create, host and manage your Appstrax Services API here: https://codecapsules.io/
Installation
Add @appstrax/services as a project dependency:
npm install @appstrax/servicesSetup
Initialize the appstrax-services library:
// import the services library
import { AppstraxServices } from '@appstrax/services';
// initialize the service
await AppstraxServices.init({
apiUrl: '' // the base URL of your Appstrax Services API
apiKey: '' // create your api-key in the Appstrax Services admin panel
});This library integrates with the Appstrax Auth API which allows you to easily interact with authentication in your web applications.
To get started import appstraxAuth into your project:
import { appstraxAuth } from '@appstrax/services/auth';Registration
try {
const result: AuthResult = await appstraxAuth.register({
email: '[email protected]',
password: '<password>',
data: {
// any additional/custom user fields
'name': 'Joe',
'surname': 'Soap',
...
}
});
console.log('Successfully Registered: ', result.user?.email);
} catch (err) {
// something went wrong while trying to Register the User
handleError(err);
}Login
try {
const result: AuthResult = await appstraxAuth.login({
email: '[email protected]',
password: '<password>',
});
console.log('Logged In As: ', result.user?.email);
} catch (err) {
// something went wrong while logging in
handleError(err);
}SSO (Google and Microsoft)
Add an SSO account in the Appstrax admin panel (Auth Configuration → SSO Settings), then:
import { appstraxAuth, SSO, AuthStatus } from '@appstrax/services/auth';
// On your login page / app boot (also runs automatically during AppstraxServices.init):
const ssoResult = await appstraxAuth.handleSsoRedirect();
if (ssoResult?.status === AuthStatus.linkRequired) {
// Existing email/password user — ask for password, then:
await appstraxAuth.linkSsoAccount(password, ssoResult.pendingLinkToken);
} else if (ssoResult?.status === AuthStatus.authenticated) {
console.log('Signed in with Google', ssoResult.user?.email);
}
// If the SSO redirect was consumed automatically during AppstraxServices.init()
// rather than via the explicit call above, check for a failure here:
const ssoError = appstraxAuth.getSsoRedirectError();
if (ssoError) {
// show an SSO failure message
}
// Start sign-in (redirect by default)
await appstraxAuth.loginWith(SSO.google);
await appstraxAuth.loginWith(SSO.microsoft);
// Or use a popup
await appstraxAuth.loginWith(SSO.google, { mode: 'popup' });
// Optionally check which providers are enabled
const providers = await appstraxAuth.getSsoProviders();Several accounts for one provider
An install can hold more than one account per provider - one Microsoft app
registration per customer, say. Each has an accountKey you pass when starting
a sign-in:
await appstraxAuth.loginWith(SSO.microsoft, { accountKey: 'companyx' });
// The accounts this install offers, for rendering buttons:
const accounts = await appstraxAuth.getSsoAccounts();
// [{ key: 'companyx', provider: 'microsoft', displayName: 'Company X', enabled: true }]Omitting accountKey keeps working: the API falls back to the provider's
default account, so apps built before this existed are unaffected.
Sending people to the right account
When the address decides which organisation someone belongs to, ask first:
const discovery = await appstraxAuth.discoverSso(email);
if (discovery.required) {
// e.g. "Company X uses Microsoft to sign in"
await appstraxAuth.loginWith(SSO[discovery.provider], {
accountKey: discovery.accountKey,
});
} else {
// show the password field
}required: false means the ordinary password form applies. It says nothing
about whether an account exists.
Domains that must use SSO
An operator can require a domain to sign in through one account. For those
addresses every email/password call - login, register, forgot password, reset
password, change password - is refused with 403 and the message
ssoRequired. The rejection names the account to use:
import { ssoRequirementFrom } from '@appstrax/services/auth';
try {
await appstraxAuth.login({ email, password });
} catch (err) {
const requirement = ssoRequirementFrom(err);
if (requirement) {
await appstraxAuth.loginWith(SSO[requirement.provider], {
accountKey: requirement.accountKey,
});
return;
}
handleError(err);
}Successful SSO still returns Appstrax access tokens (same JWTs validated via JWKS on your APIs). Google tokens are never used as API credentials.
Sign-in is protected with PKCE: the one-time code returned to your app is bound to the browser session that started the flow, so an intercepted code cannot be redeemed by anything else. This is automatic and needs no code changes on your side.
This binding is mandatory — the Appstrax API rejects a sign-in that is not bound — so your app must be served from a secure context. That means HTTPS, or http://localhost during development, because browsers only expose the Web Crypto API there. appstraxAuth.loginWith throws with an explanation if it is called from anywhere else.
Watch out for this when testing on a phone or another machine over your local network: http://192.168.1.5:4200 is not a secure context, so Google sign-in will fail there even though http://localhost:4200 works. Use an HTTPS dev server or a tunnel for that case.
Google sign-in needs @appstrax/services 0.4.0 or later against a current
Appstrax API. Microsoft sign-in, several accounts per provider, discoverSso
and ssoRequirementFrom need 0.6.0 or later.
Forgot Password
try {
await appstraxAuth.forgotPassword({
email: '[email protected]',
});
console.log('Email Sent.');
} catch (err) {
// something went wrong sending the email
handleError(err);
}An email will be sent to the user with a password reset code, this code is only valid for 24 hours.
Reset Password
try {
await appstraxAuth.resetPassword({
email: '[email protected]',
code: '<code>'
password: '<password>',
});
console.log('Email Sent.');
} catch (err) {
// something went wrong resetting the password
handleError(err);
}The password is now reset, however the user will now need to login with their new password.
Change Password
try {
await appstraxAuth.changePassword({
password: '<currentPassword>',
newPassword: '<newPassword>',
});
console.log('Password Updated.');
} catch (err) {
// something went wrong changing the password
handleError(err);
}Users can only change their password if they are already authenticated.
Save User Data/Profile
try {
const user: User = await appstraxAuth.saveUserData({
name: 'James',
surname: 'Soap',
age: 29,
career: 'Software Engineer',
});
console.log('Data Updated For: ', user?.email);
} catch (err) {
// something went wrong updating the User data
handleError(err);
}Users can only update their data if they are already authenticated.
Logout
try {
await appstraxAuth.logout():
console.log('Logout Successful');
} catch (err) {
// something went wrong while logging out
handleError(err);
}Auth Error Messages
export enum AuthErrors {
// registration errors
emailAddressAlreadyExists = 'emailAddressAlreadyExists',
badlyFormattedEmailAddress = 'badlyFormattedEmailAddress',
noPasswordSupplied = 'noPasswordSupplied',
// login errors
invalidEmailOrPassword = 'invalidEmailOrPassword',
userBlocked = 'userBlocked',
invalidTwoFactorAuthCode = 'invalidTwoFactorAuthCode',
// forgot/reset password errors
emailAddressDoesNotExist = 'emailAddressDoesNotExist',
invalidResetCode = 'invalidResetCode',
// unknown errors
unexpectedError = 'unexpectedError',
}This library integrates with the Appstrax Database API which allows you to easily interact with your database in your web applications.
To get started import appstraxDb into your project:
import { appstraxDb } from '@appstrax/services/database';A collection has to exist on the API before you can read from or write to it, and each collection carries an access policy that decides what a given user may do with it. Both are set up in the Appstrax admin panel under Database > Collections — there is no API for them in this library, which is intended to run in the browser. Reading or writing a collection that has not been set up fails the same way as reading one you do not have access to; see Database Error Messages.
Create
// create a new Document, returns a DocumentDto from the 'profiles' collection
try {
const document: DocumentDto = await appstraxDb.create('profiles', {
name: 'John',
surname: 'Doe',
career: 'Software Engineer',
});
console.log('Document Created: ', document?.id);
} catch (err) {
// the create was rejected — show the user why
showMessage(describeDatabaseError(err));
}Edit
// edit documents
try {
const document: DocumentDto = await appstraxDb.edit('profiles', 'id', {
name: 'John Frederick',
surname: 'Doe',
career: 'Software Engineer',
});
console.log('Document Edited:', document?.id);
} catch (err) {
if (isConflict(err)) {
// somebody else changed this document first — reload before retrying
}
showMessage(describeDatabaseError(err));
}Note that edit replaces the whole document rather than merging into it, so send
every field you want to keep. Fields the collection's policy manages itself (an
owner id, for example) are always rewritten by the server, and fields the policy
marks as unchangeable keep their existing value whatever you send.
Delete
// delete documents
try {
await appstraxDb.delete('profiles', 'id');
console.log('Document Deleted.');
} catch (err) {
// the delete was rejected — show the user why
showMessage(describeDatabaseError(err));
}Find By Id
// findById returns a DocumentDto from the 'profiles' collection
try {
const document: DocumentDto = await appstraxDb.findById('profiles', 'id');
console.log('Document Found: ', document?.id);
} catch (err) {
// a document you may not see is reported exactly like a missing one
showMessage(describeDatabaseError(err));
}Find
// find returns a FindResultDto<DocumentDto>
try {
const documents: FindResultDto = await appstraxDb.find('profiles');
documents.data.forEach((doc) => {
console.log(doc.id);
});
} catch (err) {
// the query was rejected — show the user why
showMessage(describeDatabaseError(err));
}
// find accepts a FetchQuery as in examples above
// You can create compound queries as above
// Here we search for documents where dogs >= 4
try {
const documents: FindResultDto = await appstraxDb.find('profiles', {
where: { dogs: { [Operator.GTE]: 4 } },
});
documents.data.forEach((doc) => {
console.log(doc.id);
});
} catch (err) {
// the query was rejected — show the user why
showMessage(describeDatabaseError(err));
}Sorting and paging
order, offset and limit round out the FetchQuery:
const documents: FindResultDto = await appstraxDb.find('profiles', {
where: { career: { [Operator.LIKE]: 'Software' } },
order: { surname: OrderDirection.ASC },
offset: 40,
limit: 20,
});
console.log(documents.count); // total matching documents, ignoring offset/limitlimit maxes out at 1000 and defaults to 1000 when omitted. Larger values,
zero and negative values are clamped by the server rather than rejected, so always
read limit and offset back off the result to see what was actually applied:
const documents = await appstraxDb.find('profiles', { limit: 5000 });
console.log(documents.limit); // 1000Only the documents a user is allowed to see are counted and returned, so count
is that user's total, not the collection's.
CRUD Service
The CrudService is a abstract class which wraps the Create, Read, Update and Delete functions in appstraxDb. The CrudService is declared with a model which extends the Model class, this model is the type that the service Creates, Reads, Updates and Deletes.
Similarly to appstraxDb, the CrudService uses a collection name which represents the "table" that the data is stored in on the server.
To get started import CrudService & Model into your project:
import { CrudService, Model } from '@appstrax/services/database';Create your custom Model & Service:
// Profile is an example of the 'type' that the CrudService is declared with
// NB. each field requires a default value. (fieldName = defaultValue)
export class Profile extends Model {
name: string = '';
surname: string = '';
career: string = '';
}
// ProfileService is an example of how to implement the CrudService
// 'profiles' is the collection name
export class ProfileService extends CrudService<Profile> {
constructor() {
super('profiles', Profile);
}
}We can now use the ProfileService as follows:
const profileService = new ProfileService();
var createdProfileId: string = '';
// example of create
try {
const profile = new Profile();
profile.name = 'Jane';
profile.surname = 'Doe';
profile.career = 'Software Engineer';
// the `save` function is used to create and update
let createdProfile = await profileService.save(profile);
createdProfileId = createdProfile.id;
console.log('Profile Created: ', createdProfileId);
} catch (err) {
// the save was rejected — show the user why
showMessage(describeDatabaseError(err));
}
// example of findById, returns an instantiated `Profile`, or throws if the
// profile does not exist or this user is not allowed to see it.
try {
const profile = await profileService.findById(createdProfileId);
console.log('Profile Fetched: ', profile);
} catch (err) {
// the read was rejected — show the user why
showMessage(describeDatabaseError(err));
}
// example of find, returns a FindResultDto
try {
const findResult = await profileService.find(); // find all profiles
const profiles = findResult.data;
console.log('Profiles Fetched: ', profiles);
} catch (err) {
// the read was rejected — show the user why
showMessage(describeDatabaseError(err));
}
// example of find with a FetchQuery
try {
const findResult = await profileService.find({
where: { career: { [Operator.LIKE]: 'Software' } },
});
const profiles = findResult.data;
console.log('Profiles Fetched: ', profiles);
} catch (err) {
// the read was rejected — show the user why
showMessage(describeDatabaseError(err));
}
// example of delete
try {
await profileService.delete(createdProfileId);
console.log('Profile Deleted: ', createdProfileId);
} catch (err) {
// the delete was rejected — show the user why
showMessage(describeDatabaseError(err));
}Every collection carries an access policy, so a request can be refused for reasons the caller cannot see — a rule that does not cover them, a field they may not write, or a document that belongs to somebody else. Import the helpers to turn any rejection into something you can put in front of a user:
import {
DatabaseErrors,
databaseErrorOf,
describeDatabaseError,
isPermissionDenied,
isNotFound,
isConflict,
isInvalidFields,
} from '@appstrax/services/database';The simple case — one line, any failure:
try {
await profileService.save(profile);
} catch (err) {
showMessage(describeDatabaseError(err));
}Branching on the reason:
try {
await profileService.save(profile);
} catch (err) {
if (isConflict(err)) {
// somebody else saved first; reload and let the user reapply their change
profile = await profileService.findById(profile.id);
} else if (isPermissionDenied(err)) {
showMessage('You cannot edit this profile.');
} else {
showMessage(describeDatabaseError(err));
}
}databaseErrorOf(err) returns the code directly if you would rather switch:
export enum DatabaseErrors {
// the collection's policy does not let this user do this
permissionDenied = 'permissionDenied',
// the operation needs a signed-in user and there isn't one
notAuthenticated = 'notAuthenticated',
// missing, or present but not visible to this user
notFound = 'notFound',
// the document carried fields this user may not write
invalidFields = 'invalidFields',
// the query or the request itself was rejected as invalid
invalidQuery = 'invalidQuery',
// somebody else changed the document first
conflict = 'conflict',
tooManyRequests = 'tooManyRequests',
// no response at all: offline, timeout, or blocked by CORS
networkError = 'networkError',
unexpectedError = 'unexpectedError',
}Three of these are worth understanding properly:
notFounddoes not mean deleted. The API returns the same response for a document that does not exist and one that exists but belongs to another user, on purpose — otherwise you could probe for other people's document ids. Never tell the user the record was removed; tell them it could not be found or is not theirs.conflictis worth retrying, once. It means an edit landed between your read and your write. Re-read the document, reapply the change, and save again. Retrying blindly without re-reading would overwrite whoever got there first.networkErroris not a server rejection. It is the one case with no HTTP status at all, so it is safe to retry as-is. Everything else is a decision the server made and will make again.
HttpError is re-exported from the same entry point if you need the raw status
and message, and the helpers all accept unknown, so you can pass a catch
binding straight in without narrowing it first.
This library integrates with the Appstrax Storage API which allows you to easily interact with storage in your web applications.
To get started import appstraxStorage into your project:
import { appstraxStorage } from '@appstrax/services/storage';Upload File
// upload File
try {
const result = await appstraxStorage.uploadFile(file, '<folder>/', (e) => {
var percentCompleted = Math.round((e.loaded * 100) / e.total);
console.log('Percentage Completed: ', percentCompleted);
});
console.log('File Uploaded: ', result.downloadUrl);
} catch (err) {
// something went wrong while uploading the file
handleError(err);
}Delete File
// delete File using downloadUrl
try {
await appstraxStorage.deleteFile(result.downloadUrl);
console.log('File Deleted');
} catch (err) {
// something went wrong while deleting the file
handleError(err);
}The find() function accepts FetchQuery as an argument:
Fetch Query
export interface FetchQuery {
where?: Where;
order?: Order;
offset?: number;
limit?: number;
}
export interface Where {
// eslint-disable-next-line @typescript-eslint/ban-types
[key: string | Operator]: object | Operator | [] | number | string | boolean;
}
export interface Order {
[key: string]: OrderDirection;
}
export enum OrderDirection {
/** Ascending Order Direction */
ASC = 'ASC',
/** Descending Order Direction */
DESC = 'DESC',
}Query Operators
export enum Operator {
/** Equal To Operator */
EQUAL = 'EQUAL',
/** Not Equal To Operator */
NOT_EQUAL = 'NOT_EQUAL',
/** And Operator */
AND = 'AND',
/** Or Operator */
OR = 'OR',
/** Greater Than Operator */
GT = 'GT',
/** Greater Than or Equal To Operator */
GTE = 'GTE',
/** Less Than Operator */
LT = 'LT',
/** Less Than or Equal To Operator */
LTE = 'LTE',
/** Like Operator */
LIKE = 'LIKE',
/** Not Like Operator */
NOT_LIKE = 'NOT_LIKE',
/** In Operator */
IN = 'IN',
/** Contains Operator */
CONTAINS = 'CONTAINS',
}CONTAINS requires API support. The Appstrax Database API accepts it in a
query but does not yet apply it, so a CONTAINS clause currently matches nothing
rather than returning an error. Do not rely on it until your API reports otherwise.
The find() function returns a FindResultDto:
// querying the data returns a FindResultDto<DocumentDto> from the collection
export interface FindResultDto<T extends DocumentDto | Model> {
data: T[];
where: Where;
order: Order;
limit: number;
offset: number;
count: number;
}
export class DocumentDto {
id: string;
data: any = {};
createdAt: Date = null;
updatedAt: Date = null;
}