Javascript Client ​

Thank you for choosing modular-rest to build your app. You can install the client by installing the package from npm.

Install Client App ​

it assumed you already have a fronted project based on javascript, it dose not matter what framework you are using, you can use modular-rest with any javascript framework.

Just use below command:

sh
npm install @modular-rest/client
sh
yarn add @modular-rest/client

Setup the client ​

You need to setup the global configuration for the client in any initialization file of your project, for example in src/index.js file.

js
import { GlobalOptions } from "@modular-rest/client";

GlobalOptions.set({
	// the base url of the server, it should match with the server address
	host: 'http://localhost:8080',
});

Use the client ​

Now you can use the client in your project, for example to use the AuthService service, import it as follows:

js
import { authentication, dataProvider } from '@modular-rest/client';

// first login with any available methods.
authentication.loginWithLastSession()

// After login, you can use either the dataProvider service or other available services of the client.
const cities = await dataProvider.find<City>({
  database: 'geography',
  collection: 'cities',
  query: { population: { $gt: 1000000 } },
  options: { limit: 10, sort: { population: -1 } }
});

AuthService Service ​

The AuthService class handles the authentication process, including login, token management, and user session handling.

Importing the Service ​

To use the AuthService service, import it as follows:

typescript
import { authentication } from '@modular-rest/client';

Public Properties ​

PropertyDescription
userThe currently authenticated user, or null if no user is authenticated.
isLoginA boolean indicating if the user is currently logged in.

login() ​

Logs in the user with the provided credentials.

Arguments ​

ArgumentTypeDescription
identityIdentityTypeThe identity of the user (e.g., username or email).
passwordstringThe user's password.
optionsLoginOptionsTypeAdditional login options.

Return and Throw ​

ReturnsDescription
Promise<LoginResponseType>The login response data.
ThrowsError if the login fails.

Example ​

typescript
authentication.login('user@example.com', 'password123', { rememberMe: true })
    .then(response => {
        console.log('Login successful:', response);
    })
    .catch(error => {
        console.error('Login failed:', error);
    });

loginWithLastSession() ​

Logs in with the last session if you pass allowSave=true in the last login.

Arguments ​

ArgumentTypeDescription
tokenstringThe token for the last session (optional).

Return and Throw ​

ReturnsDescription
Promise<User>The logged-in user data.
ThrowsError if the login fails.

Example ​

typescript
authentication.loginWithLastSession()
    .then(user => {
        console.log('Logged in with last session:', user);
    })
    .catch(error => {
        console.error('Login with last session failed:', error);
    });

loginAsAnonymous() ​

Logs in as an anonymous user and retrieves a token.

Return and Throw Table:

ReturnsDescription
Promise<LoginResponseType>The login response data containing the token.
ThrowsError if the login fails.

Example ​

typescript
authService.loginAsAnonymous()
    .then(response => {
        console.log('Anonymous login successful:', response);
    })
    .catch(error => {
        console.error('Anonymous login failed:', error);
    });

logout() ​

Logs out the current user and clears the session.

Return and Throw ​

ReturnsDescription
voidNo return value.
ThrowsNone

Example ​

typescript
authentication.logout();

verifyToken() ​

Verifies the provided token.

Arguments ​

ArgumentTypeDescription
tokenstringThe token to verify.

Return and Throw ​

ReturnsDescription
Promise<VerifyTokenResponseType>The token verification response data.
ThrowsError if the token verification fails.

Example ​

typescript
authentication.verifyToken('some-jwt-token')
    .then(response => {
        console.log('Token verification successful:', response);
    })
    .catch(error => {
        console.error('Token verification failed:', error);
    });

registerIdentity() ​

Registers a user identity, the first step for creating a new account.

Arguments ​

ArgumentTypeDescription
identityIdentityTypeThe identity of the user.

Return and Throw ​

ReturnsDescription
Promise<BaseResponseType>The registration response data.
ThrowsError if the registration fails.

Example ​

typescript
authentication.registerIdentity({ idType: 'email', id: 'user@example.com' })
    .then(response => {
        console.log('Identity registered:', response);
    })
    .catch(error => {
        console.error('Identity registration failed:', error);
    });

validateCode() ​

Validates the provided code.

Arguments ​

ArgumentTypeDescription
codestringThe code to validate.

Return and Throw ​

ReturnsDescription
Promise<ValidateCodeResponseType>The validation response data.
ThrowsError if the validation fails.

Example ​

typescript
authentication.validateCode('123456')
    .then(response => {
        console.log('Code validation successful:', response);
    })
    .catch(error => {
        console.error('Code validation failed:', error);
    });

submitPassword() ​

Submits a password, the third step for creating a new account.

Arguments ​

ArgumentTypeDescription
optionsobjectThe password submission options.
options.idstringThe user identity.
options.passwordstringThe user's password.
options.codestringThe verification code.

Return and Throw ​

ReturnsDescription
Promise<BaseResponseType>The password submission response data.
ThrowsError if the submission fails.

Example ​

typescript
authentication.submitPassword({ id: 'user@example.com', password: 'newpassword', code: '123456' })
    .then(response => {
        console.log('Password submitted successfully:', response);
    })
    .catch(error => {
        console.error('Password submission failed:', error);
    });

changePassword() ​

Changes the user's password.

Arguments ​

ArgumentTypeDescription
optionsobjectThe password change options.
options.idstringThe user identity.
options.passwordstringThe new password.
options.codestringThe verification code.

Return and Throw ​

ReturnsDescription
Promise<BaseResponseType>The password change response data.
ThrowsError if the change fails.

Example ​

typescript
authentication.changePassword({ id: 'user@example.com', password: 'newpassword', code: '123456' })
    .then(response => {
        console.log('Password changed successfully:', response);
    })
    .catch(error => {
        console.error('Password change failed:', error);
    });

DataProvider Service Documentation ​

The DataProvider service is a singleton class that provides methods for interacting with a database through HTTP requests. It offers various operations such as finding, updating, inserting, and aggregating data.

To use the DataProvider service, import it as follows:

typescript
import { dataProvider } from '@modular-rest/client'

list() ​

Returns an object containing pagination information and controller methods for fetching paginated data.

Arguments ​

NameTypeDescription
findOptionFindQueryTypeQuery options for finding data
paginationOptionObjectOptions for pagination (limit, page, onFetched)

Returns/Throws ​

TypeDescription
PaginatedResponseType<T>Object with pagination info and control methods
ErrorThrows if the HTTP request fails

Example ​

typescript
// Initialize a paginated list of red flowers
const flowerList = dataProvider.list<Flower>(
  {
    database: 'botany',
    collection: 'flowers',
    query: { color: 'red' }
  },
  { limit: 20, page: 1, onFetched: (flowers) => console.log(flowers) }
);

// Need Update pagination after initialization
await flowerList.updatePagination();

// Fetch the first page
await flowerList.fetchPage(1);

find() ​

Retrieves an array of documents from the specified database and collection.

Arguments ​

NameTypeDescription
optionsFindQueryTypeQuery options for finding data

Returns/Throws ​

TypeDescription
Promise<Array<T>>Resolves to an array of found documents
ErrorThrows if the HTTP request fails

Example ​

typescript
const cities = await dataProvider.find<City>({
  database: 'geography',
  collection: 'cities',
  query: { population: { $gt: 1000000 } },
  options: { limit: 10, sort: { population: -1 } }
});

findByIds() ​

Retrieves documents by their IDs from the specified database and collection.

Arguments ​

NameTypeDescription
optionsFindByIdsQueryTypeOptions for finding documents by IDs

Returns/Throws ​

TypeDescription
Promise<Array<T>>Resolves to an array of found documents
ErrorThrows if the HTTP request fails

Example ​

typescript
const specificCities = await dataProvider.findByIds<City>({
  database: 'geography',
  collection: 'cities',
  ids: ['city123', 'city456', 'city789'],
  accessQuery: { country: 'USA' }
});

findOne() ​

Retrieves a single document from the specified database and collection.

Arguments ​

NameTypeDescription
optionsFindQueryTypeQuery options for finding a single document

Returns/Throws ​

TypeDescription
Promise<T>Resolves to the found document
ErrorThrows if the HTTP request fails

Example ​

typescript
const capital = await dataProvider.findOne<City>({
  database: 'geography',
  collection: 'cities',
  query: { isCapital: true, country: 'France' }
});

count() ​

Counts the number of documents matching the specified query.

Arguments ​

NameTypeDescription
optionsFindQueryTypeQuery options for counting documents

Returns/Throws ​

TypeDescription
Promise<number>Resolves to the count of matching documents
ErrorThrows if the HTTP request fails

Example ​

typescript
const roseCount = await dataProvider.count({
  database: 'botany',
  collection: 'flowers',
  query: { genus: 'Rosa' }
});

updateOne() ​

Updates a single document in the specified database and collection.

Arguments ​

NameTypeDescription
optionsUpdateQueryTypeQuery and update options for modifying a document

Returns/Throws ​

TypeDescription
Promise<any>Resolves to the result of the update operation
ErrorThrows if the HTTP request fails

Example ​

typescript
const updateResult = await dataProvider.updateOne({
  database: 'geography',
  collection: 'cities',
  query: { name: 'New York' },
  update: { $set: { population: 8500000 } }
});

insertOne() ​

Inserts a single document into the specified database and collection.

Arguments ​

NameTypeDescription
optionsInsertQueryTypeOptions for inserting a new document

Returns/Throws ​

TypeDescription
Promise<any>Resolves to the result of the insert operation
ErrorThrows if the HTTP request fails

Example ​

typescript
const newFlower = await dataProvider.insertOne({
  database: 'botany',
  collection: 'flowers',
  doc: { name: 'Sunflower', genus: 'Helianthus', color: 'yellow' }
});

removeOne() ​

Removes a single document from the specified database and collection.

Arguments ​

NameTypeDescription
optionsFindQueryTypeQuery options for removing a document

Returns/Throws ​

TypeDescription
Promise<any>Resolves to the result of the remove operation
ErrorThrows if the HTTP request fails

Example ​

typescript
const removeResult = await dataProvider.removeOne({
  database: 'geography',
  collection: 'cities',
  query: { name: 'Ghost Town', population: 0 }
});

aggregate() ​

Performs an aggregation operation on the specified database and collection.

Arguments ​

NameTypeDescription
optionsAggregateQueryTypeOptions for the aggregation pipeline

Returns/Throws ​

TypeDescription
Promise<Array<T>>Resolves to the result of the aggregation
ErrorThrows if the HTTP request fails

Example ​

typescript
const flowerStats = await dataProvider.aggregate<FlowerStats>({
  database: 'botany',
  collection: 'flowers',
  pipelines: [
    { $group: { _id: '$color', count: { $sum: 1 } } },
    { $sort: { count: -1 } }
  ],
  accessQuery: { genus: { $in: ['Rosa', 'Tulipa'] } }
});

FileProvider Service Documentation ​

The FileProvider service is responsible for managing file operations such as uploading, removing, and retrieving file information. It provides methods to interact with files on the server and manage file metadata.

To use the FileProvider service, import it as follows:

javascript
import { fileProvider } from '@modular-rest/client'

uploadFile() ​

Uploads a file to the server.

Arguments ​

NameTypeDescription
filestring | BlobThe file to be uploaded
onProgress(progressEvent: ProgressEvent) => voidCallback function to track upload progress
tagstring (optional)Tag for the file, defaults to "untagged"

Return and Throw ​

TypeDescription
Promise<FileDocument>Resolves with the uploaded file document
ErrorThrows an error if the upload fails

Example ​

javascript
const file = new Blob(['Hello, World!'], { type: 'text/plain' });
const onProgress = (event) => console.log(`Upload progress: ${event.loaded / event.total * 100}%`);

fileProvider.uploadFile(file, onProgress, 'documents')
  .then(fileDoc => console.log('Uploaded file:', fileDoc))
  .catch(error => console.error('Upload failed:', error));

uploadFileToURL() ​

Uploads a file to a specific URL.

Arguments ​

NameTypeDescription
urlstringThe URL to upload the file to
filestringBlob
bodyany (optional)Additional data to be sent with the request
onProgress(progressEvent: ProgressEvent) => voidCallback function to track upload progress
tagstringTag for the file

Return and Throw ​

TypeDescription
Promise<any>Resolves with the response from the server
ErrorThrows an error if the upload fails

Example ​

javascript
const url = 'https://api.example.com/upload';
const file = new Blob(['Flower data'], { type: 'text/plain' });
const body = { category: 'flora' };
const onProgress = (event) => console.log(`Upload progress: ${event.loaded / event.total * 100}%`);

fileProvider.uploadFileToURL(url, file, body, onProgress, 'botanical')
  .then(response => console.log('Upload response:', response))
  .catch(error => console.error('Upload failed:', error));

removeFile() ​

Removes a file from the server.

Arguments ​

NameTypeDescription
idstringThe ID of the file to be removed

Return and Throw ​

TypeDescription
Promise<any>Resolves with the response from the server
ErrorThrows an error if the removal fails

Example ​

javascript
const fileId = '123456789';

fileProvider.removeFile(fileId)
  .then(response => console.log('File removed successfully:', response))
  .catch(error => console.error('File removal failed:', error));

Generates a URL for accessing a file.

Arguments ​

NameTypeDescription
fileDoc{ fileName: string; format: string; tag: string }File document object
overrideUrlstring (optional)Optional URL to override the default
rootPathstring (optional)Root path for the file, defaults to "assets"

Return and Throw ​

TypeDescription
stringThe generated URL for the file

Example ​

javascript
const fileDoc = {
  fileName: 'city_map.jpg',
  format: 'images',
  tag: 'maps'
};

const fileUrl = fileProvider.getFileLink(fileDoc);
console.log('File URL:', fileUrl);

getFileDoc() ​

Retrieves a file document by its ID and user ID.

Arguments ​

NameTypeDescription
idstringThe ID of the file
userIdstringThe ID of the user who owns the file

Return and Throw ​

TypeDescription
Promise<FileDocument>Resolves with the file document
ErrorThrows an error if the file document cannot be found

Example ​

javascript
const fileId = '987654321';
const userId = 'user123';

fileProvider.getFileDoc(fileId, userId)
  .then(fileDoc => console.log('File document:', fileDoc))
  .catch(error => console.error('Failed to retrieve file document:', error));

getFileDocsByTag() ​

Retrieves file documents by tag and user ID.

Arguments ​

NameTypeDescription
tagstringThe tag to search for
userIdstringThe ID of the user who owns the files

Return and Throw ​

TypeDescription
Promise<FileDocument[]>Resolves with an array of file documents
ErrorThrows an error if the file documents cannot be found

Example ​

javascript
const tag = 'flowers';
const userId = 'user456';

fileProvider.getFileDocsByTag(tag, userId)
  .then(fileDocs => console.log('File documents:', fileDocs))
  .catch(error => console.error('Failed to retrieve file documents:', error));

FunctionProvider Service Documentation ​

The FunctionProvider service allows executing server-side functions from the client. It provides a simple interface to run named functions with arguments and receive the result.

TIP

To learn how to define functions on the server, check out the Server-side Functions documentation.

To use the FunctionProvider service, import it as follows:

javascript
import { functionProvider } from '@modular-rest/client'

run() ​

Executes a server-side function.

Arguments ​

NameTypeDescription
options{ name: string; args: any }Object containing function name and arguments

Return and Throw ​

TypeDescription
Promise<any>Resolves with the result returned by the server-side function
ErrorThrows an error if the function execution fails or returns an error

Example ​

javascript
const options = {
  name: 'calculateSum',
  args: { a: 10, b: 20 }
};

functionProvider.run(options)
  .then(result => console.log('Function result:', result))
  .catch(error => console.error('Function execution failed:', error));

This would be the HttpClient service documentation