@appstrax/services
v0.1.8
Published
The Appstrax javascript npm library
Downloads
177
Readme
@appstrax/services
Table of Contents
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/services
Setup
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);
}
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',
}
User Service
This library integrates with the Appstrax Auth API which allows you to easily manage the users in your web applications.
To get started import appstraxUsers
into your project:
import { appstraxUsers } from '@appstrax/services/auth';
Public Availability
To enable public access to users go to:
Admin Panel -> Configuration tab -> Public Access -> toggle 'Allow Public Access'
Querying Users
The appstraxUsers.find() function takes a FetchQuery as an argument and returns a FindResultDto
Examples
A query to search for the users table similar to:
try {
const result: FindResultDto = await appstraxUsers.find({
where: { email: { [Operator.LIKE]: "Joe" } },
order: { email: "ASC" }
offset: 0,
limit: 5,
});
this.totalUsers = result.count;
this.userData = result.data;
} catch (err) {
// something went wrong while querying the database
handleError(err);
}
A query to search for the users table similar to:
try {
const result: FindResultDto = await appstraxUsers.find({
where: {
[Operator.OR]: [
{ email: { [Operator.LIKE]: 'Joe' } },
{ name: { [Operator.LIKE]: 'Joe' } },
{ surname: { [Operator.LIKE]: 'Joe' } },
],
},
offset: 0,
limit: 5,
});
this.totalUsers = result.count;
this.userData = result.data;
} catch (err) {
// something went wrong while querying the database
handleError(err);
}
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';
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) {
// something went wrong while creating the document
handleError(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) {
// something went wrong while updating the document
handleError(err);
}
Delete
// delete documents
try {
await appstraxDb.delete('profiles', 'id');
console.log('Document Deleted.');
} catch (err) {
// something went wrong while deleting the document
handleError(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) {
// something went wrong while querying the 'profiles' collection
handleError(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) {
// something went wrong while querying the 'profiles' collection
handleError(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) {
// something went wrong while querying the 'profiles' collection
handleError(err);
}
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) {
// something went wrong while creating the profile
handleError(err);
}
// example of findById, returns an instantiated `Profile` or null.
try {
const profile = await profileService.findById(createdProfileId);
console.log('Profile Fetched: ', profile);
} catch (err) {
// something went wrong when fetching
handleError(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) {
// something went wrong when fetching
handleError(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) {
// something went wrong when fetching
handleError(err);
}
// example of delete
try {
await profileService.delete(createdProfileId);
console.log('Profile Deleted: ', createdProfileId);
} catch (err) {
// something went wrong while deleting the profile
handleError(err);
}
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',
}
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;
}