@appstrax/admin-services
v0.1.9
Published
The Appstrax Admin NodeJS JavaScript Library
Downloads
145
Readme
Appstrax Admin Services Node.js Library
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, first send an email to [email protected] and we'll help create, host and manage your Appstrax API here: https://codecapsules.io/
Add @appstrax/admin-services
as a project dependency:
npm install @appstrax/admin-services
Initialize the appstrax-admin-services
libraries:
// import the services library
import { AppstraxServices } from '@appstrax/admin-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 and is used in nodejs applications.
To get started import appstraxUsers
into your project:
import { appstraxUsers, User } from '@appstrax/admin-services/auth';
Create User
try {
let user = new User();
user.email = email;
user.password = password;
user.data = {
name: name,
surname: surname,
... // any other user profile fields
};
user = await appstraxUsers.create(user);
console.log('Successfully Created: ', user.id);
} catch (err) {
// something went wrong while trying to create the User
handleError(err);
}
Update User
try {
user.data = {
name: name,
surname: surname,
age: 29,
career: 'Software Engineer',
};
user = await appstraxUsers.update(user);
console.log('Successfully Updated: ', user.data);
} catch (err) {
// something went wrong while trying to update the User
handleError(err);
}
Delete User
try {
await appstraxUsers.delete(user.id);
console.log('Successfully Deleted.');
} catch (err) {
// something went wrong while trying to delete the User
handleError(err);
}
Change User Password
try {
await appstraxUsers.changePassword(user.id, newPassword);
console.log('Successfully Changed Password.');
} catch (err) {
// something went wrong changing the password
handleError(err);
}
Find User by Id
try {
user = await appstraxUsers.findById(user.id);
console.log('Successfully Found: ', user);
} catch (err) {
// something went wrong while querying the collection
handleError(err);
}
Querying Users With Find
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 and is used in nodejs applications.
To get started import appstraxDb
into your project:
import { appstraxDb } from '@appstrax/admin-services/database';
Create Document
// create a new Document in the 'profiles' collection, returns a DocumentDto
try {
const document: DocumentDto = await appstraxDb.create('profiles', {
name: 'John',
surname: 'Doe',
career: 'Software Engineer',
});
console.log('Document Created: ', document);
} catch (err) {
// something went wrong while creating the document
handleError(err);
}
Edit Document
// edit documents
try {
const document: DocumentDto = await appstraxDb.edit('profiles', document.id, {
name: 'John Frederick',
surname: 'Doe',
career: 'Software Engineer',
});
console.log('Document Edited:', document);
} catch (err) {
// something went wrong while editing the document
handleError(err);
}
Delete Document
// delete documents
try {
await appstraxDb.delete('profiles', document.id);
console.log('Document Deleted.');
} catch (err) {
// something went wrong while deleting the document
handleError(err);
}
Find Document By Id
// findById returns a DocumentDto from the 'profiles' collection
try {
const document: DocumentDto = await appstraxDb.findById('profiles', documentId);
console.log('Document Found: ', document);
} catch (err) {
// something went wrong while querying the 'profiles' collection
handleError(err);
}
Find Documents
// find() returns a FindResultDto<DocumentDto>
try {
const result: FindResultDto = await appstraxDb.find('profiles');
console.log('Documents Found: ', results.data);
} catch (err) {
// something went wrong while querying the 'profiles' collection
handleError(err);
}
// find() accepts an optional FetchQuery as its second parameter
// in example below we find all documents where `career` includes 'Software'
try {
const result: FindResultDto = await appstraxDb.find('profiles', {
where: { career: { [Operator.LIKE]: 'Software' } },
});
console.log('Documents Found: ', result.data);
} 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/admin-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 and is used in nodejs applications.
To get started import appstraxStorage
into your project:
import { appstraxStorage } from '@appstrax/admin-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);
}
Fetch Directory
// Fetch Directory by path
try {
const directoryDto = await appstraxStorage.fetchDirectory('');
console.log('Directory: ', directoryDto);
} catch (err) {
// something went wrong while fetching the directory
handleError(err);
}
The appstraxStorage.fetchDirectory
function returns a DirDto
as defined below
interface DirDto {
totalFiles: number;
dirItems: DirItemDto[];
}
interface DirItemDto {
name: string; // the name of the file or folder
type: 'folder' | 'file';
}
Create Directory
// Create Directory by path
try {
await appstraxStorage.createDirectory('/DirectoryA/DirectoryB');
} catch (err) {
// something went wrong while creating the directory
handleError(err);
}
Delete Directory
// Delete Directory by path
try {
await appstraxStorage.deleteDirectory('/DirectoryA/DirectoryB');
} catch (err) {
// something went wrong while deleting the directory
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 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;
}