npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@magentrix-corp/magentrix-sdk

v1.1.10

Published

TypeScript SDK for Magentrix APIs with dual authentication modes, automatic session management, CRUD operations, and Vue 3 integration

Downloads

1,580

Readme

Magentrix SDK for JavaScript

A TypeScript-based SDK for seamless integration with Magentrix APIs. This SDK provides a convenient interface for authentication, CRUD operations, and custom queries with built-in session management and error handling.

Features

  • Dual Authentication Modes: Token-based (dev) and cookie-based (production) authentication
  • Automatic Session Management: Token refresh with configurable expiration handling
  • CRUD Operations: Create, read, update, delete operations for entities
  • Custom Queries: Execute custom queries and retrieve data by ID
  • Vue 3 Integration: Dedicated composable for Vue.js applications
  • TypeScript Support: Full type definitions included
  • Error Handling: Custom error classes with optional global error callbacks
  • ESM & CommonJS: Supports both module formats

Installation

npm install @magentrix-corp/magentrix-sdk

Quick Start

Vue 3 Project Template (Recommended)

The fastest way to start a new Vue.js project with Magentrix SDK:

npm create @magentrix-corp/iris-app-template@latest my-app
cd my-app
npm install
npm run dev

Learn more: Create Iris App Template


JavaScript/TypeScript

import { MagentrixClient, MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: '<your-refresh-token>',
  isDevMode: true // Use token-based auth
}

const dataService = new MagentrixClient(config)

// Get current user information
try {
  const userInfo = await dataService.getUserInfo()
  console.log('Logged in as:', userInfo.name)
  console.log('Role:', userInfo.roleType)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Failed to get user info:', error.message)
  }
}

// Query data - session is automatically created when needed
try {
  const result = await dataService.query('SELECT Id, Name FROM Account')
  console.log(result.data) // Array of account objects

  // Access individual records
  result.data.forEach(account => {
    console.log(account.Id, account.Name)
  })
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

// Retrieve by ID
try {
  const result = await dataService.retrieve('00I00000000003x0001')
  console.log(result.record) // The account object
  console.log('Name:', result.record.Name)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Retrieve failed:', error.message)
  }
}

Vue 3

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
import { useMagentrixSdk } from '@magentrix-corp/magentrix-sdk/vue'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: '<your-refresh-token>',
  isDevMode: true
}

const dataService = useMagentrixSdk().getInstance(config)
const account = ref<any>(null)
const error = ref<string | null>(null)

onMounted(async () => {
  try {
    // Session is automatically created when needed
    account.value = (await dataService.retrieve('00I00000000003x0001')).record
    console.log(account.value)
  } catch (err) {
    if (err instanceof MagentrixError) {
      error.value = err.message
      console.error('Failed to retrieve account:', err.message)
    }
  }
})
</script>

<template>
  <div>
    <div v-if="error" class="error">{{ error }}</div>
    <div v-else-if="account">
      <h1>{{ account.Name }}</h1>
      <p>{{ account.Email }}</p>
    </div>
  </div>
</template>

Configuration

MagentrixConfig

| Property | Type | Required | Description | |----------|------|----------|-------------| | baseUrl | string | Yes | Base URL of your Magentrix instance (e.g., 'https://your-portal-domain.com') | | refreshToken | string | No | Refresh token for authentication. Required when isDevMode: true | | isDevMode | boolean | No | Enable token-based authentication (default: false). See Authentication Modes |

Authentication Modes

The SDK supports two authentication modes controlled by the isDevMode flag:

Development Mode (isDevMode: true)

Use Case: External applications, mobile apps, or development environments

Behavior:

  • Uses token-based authentication with Bearer tokens
  • Automatically refreshes tokens before they expire (30-second buffer)
  • Validates session on every API call
  • Requires refreshToken in configuration
import { MagentrixClient, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: '<your-refresh-token>',
  isDevMode: true
}

const dataService = new MagentrixClient(config)

Production Mode (isDevMode: false or not set)

Use Case: Web applications using ASP.NET Forms Authentication

Behavior:

  • Uses cookie-based authentication (ASP.NET session cookies)
  • No bearer tokens sent in requests
  • No automatic session validation
  • Automatically redirects to login page when session expires
  • No refreshToken required
import { MagentrixClient, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  isDevMode: false // or omit this property
}

const dataService = new MagentrixClient(config)

API Reference

Session Management

createSession(refreshToken?: string): Promise<SessionInfo>

Creates a new session using the refresh token.

Note: You typically don't need to call this method directly. The SDK automatically creates and refreshes sessions when needed.

import { MagentrixClient, MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: '<your-refresh-token>',
  isDevMode: true
}

const dataService = new MagentrixClient(config)

// Optional: Manually create session if needed
try {
  const session = await dataService.createSession()
  console.log(session.token)      // Bearer token
  console.log(session.expires_in) // Seconds until expiration
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Session creation failed:', error.message)
  }
}

Parameters:

  • refreshToken (optional): Override the refresh token from config

Returns: SessionInfo object with token and expires_in

Throws: MagentrixError if token is invalid or expired

Query Operations

query(query: string): Promise<any>

Execute a custom query using Magentrix query language.

import { MagentrixError } from '@magentrix-corp/magentrix-sdk'

try {
  // Standard query - returns object with 'data' property containing array of records
  const result = await dataService.query('SELECT Id, Name, Email FROM Contact WHERE Status = "Active"')
  console.log(result.data) // Array of contact objects

  // Access individual records
  result.data.forEach(contact => {
    console.log(contact.Id, contact.Name, contact.Email)
  })
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

try {
  // Aggregate query - returns object with 'data' property containing aggregate results
  const result = await dataService.query('SELECT COUNT(Id) as TotalAccounts FROM Account')
  console.log(result.data.TotalAccounts) // Number value
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

try {
  // Multiple aggregates
  const result = await dataService.query(`
    SELECT
      COUNT(Id) as TotalAccounts,
      SUM(AnnualRevenue) as TotalRevenue,
      AVG(AnnualRevenue) as AverageRevenue
    FROM Account
  `)
  console.log('Total:', result.data.TotalAccounts)
  console.log('Sum:', result.data.TotalRevenue)
  console.log('Average:', result.data.AverageRevenue)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

Parameters:

  • query: Query string in Magentrix query language

Returns: Object with the following structure:

  • For standard queries: { data: Array<Object> } - Array of records with selected fields
  • For aggregate queries: { data: Object } - Object with aggregate field names as properties

Throws: MagentrixError if query is empty or invalid


retrieve(id: string): Promise<any>

Retrieve a single record by ID.

import { MagentrixError } from '@magentrix-corp/magentrix-sdk'

try {
  // Retrieve returns an object with a 'record' property
  const result = await dataService.retrieve('00I00000000003x0001')
  const account = result.record

  console.log('Account Name:', account.Name)
  console.log('Account Email:', account.Email)
  console.log('Account Status:', account.Status)

  // Or destructure directly
  const { record } = await dataService.retrieve('00300000000001A0001')
  console.log('Contact:', record.Name)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Retrieve failed:', error.message)
  }
}

Parameters:

  • id: Record ID to retrieve

Returns: Object with the following structure:

  • { record: Object } - The record property contains the full record data with all fields

Throws: MagentrixError if ID is not provided


CRUD Operations

create(entityName: string, data: any | any[]): Promise<any>

Create a new record or multiple records in a single API call.

import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'

// Create a single record
try {
  const newAccount = await dataService.create('Account', {
    Name: 'Acme Corporation',
    Email: '[email protected]',
    Status: 'Active'
  })
  console.log('Created ID:', newAccount.Id)
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Database error:', error.message)
    error.getErrors().forEach(err => {
      console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
    })
  } else if (error instanceof MagentrixError) {
    console.error('Create failed:', error.message)
  }
}

// Create multiple records in a single API call (RECOMMENDED for batch operations)
try {
  const newAccounts = await dataService.create('Account', [
    { Name: 'Account 1', Email: '[email protected]', Status: 'Active' },
    { Name: 'Account 2', Email: '[email protected]', Status: 'Active' },
    { Name: 'Account 3', Email: '[email protected]', Status: 'Active' }
  ])
  console.log('Created IDs:', newAccounts.map(a => a.Id))
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Database error:', error.message)
    error.getErrors().forEach(err => {
      console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
    })
  } else if (error instanceof MagentrixError) {
    console.error('Batch create failed:', error.message)
  }
}

Parameters:

  • entityName: Name of the entity (e.g., 'Account', 'Contact')
  • data: Single object or array of objects containing the record data

Returns:

  • Single object: Created record with ID
  • Array: Array of created records with IDs

Throws: MagentrixError if entityName or data is missing, DatabaseError for validation errors

Note: When creating multiple records, pass an array to make a single optimized API call instead of multiple calls.


edit(entityName: string, data: any | any[]): Promise<any>

Update an existing record or multiple records in a single API call (requires Id in data).

import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'

// Update a single record
try {
  const updated = await dataService.edit('Account', {
    Id: '00I00000000003x0001',
    Name: 'Updated Name',
    Status: 'Inactive'
  })
  console.log('Updated successfully')
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Database error:', error.message)
    error.getErrors().forEach(err => {
      console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
    })
  } else if (error instanceof MagentrixError) {
    console.error('Edit failed:', error.message)
  }
}

// Update multiple records in a single API call (RECOMMENDED for batch operations)
try {
  const updated = await dataService.edit('Account', [
    { Id: '00I00000000003x0001', Name: 'Updated Account 1', Status: 'Active' },
    { Id: '00I00000000003y0001', Name: 'Updated Account 2', Status: 'Inactive' },
    { Id: '00I00000000003z0001', Name: 'Updated Account 3', Status: 'Active' }
  ])
  console.log('Updated successfully:', updated.length, 'records')
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Database error:', error.message)
    error.getErrors().forEach(err => {
      console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
    })
  } else if (error instanceof MagentrixError) {
    console.error('Batch edit failed:', error.message)
  }
}

Parameters:

  • entityName: Name of the entity
  • data: Single object or array of objects containing the record data with Id

Returns:

  • Single object: Updated record
  • Array: Array of updated records

Throws: MagentrixError if entityName or data is missing, DatabaseError for validation errors

Note: When updating multiple records, pass an array to make a single optimized API call instead of multiple calls.


upsert(entityName: string, data: any | any[]): Promise<any>

Create or update a record or multiple records in a single API call. If Id is provided and exists, updates the record; otherwise creates a new one.

import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'

// Upsert a single record
try {
  const record = await dataService.upsert('Contact', {
    Id: '00300000000001A0001', // Optional
    Name: 'John Doe',
    Email: '[email protected]'
  })
  console.log('Upsert successful:', record.Id)
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Database error:', error.message)
    error.getErrors().forEach(err => {
      console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
    })
  } else if (error instanceof MagentrixError) {
    console.error('Upsert failed:', error.message)
  }
}

// Upsert multiple records in a single API call (RECOMMENDED for batch operations)
try {
  const records = await dataService.upsert('Contact', [
    { Id: '00300000000001A0001', Name: 'John Doe', Email: '[email protected]' }, // Will update
    { Name: 'Jane Smith', Email: '[email protected]' }, // Will create (no Id)
    { Id: '00300000000001B0001', Name: 'Bob Johnson', Email: '[email protected]' } // Will update
  ])
  console.log('Upsert successful:', records.length, 'records')
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Database error:', error.message)
    error.getErrors().forEach(err => {
      console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
    })
  } else if (error instanceof MagentrixError) {
    console.error('Batch upsert failed:', error.message)
  }
}

Parameters:

  • entityName: Name of the entity
  • data: Single object or array of objects containing the record data (Id is optional)

Returns:

  • Single object: Created or updated record
  • Array: Array of created or updated records

Throws: MagentrixError if entityName or data is missing, DatabaseError for validation errors

Note: When upserting multiple records, pass an array to make a single optimized API call instead of multiple calls.


delete(entityName: string, id: string, permanent?: boolean): Promise<any>

Delete a record by ID.

import { MagentrixError } from '@magentrix-corp/magentrix-sdk'

try {
  // Soft delete (default)
  await dataService.delete('Account', '00I00000000003x0001')
  console.log('Account deleted successfully')
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Delete failed:', error.message)
  }
}

try {
  // Permanent delete
  await dataService.delete('Account', '00I00000000003x0001', true)
  console.log('Account permanently deleted')
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Delete failed:', error.message)
  }
}

Parameters:

  • entityName: Name of the entity
  • id: Record ID to delete
  • permanent (optional): If true, permanently deletes the record (default: false)

Returns: Deletion result

Throws: MagentrixError if entityName or id is missing


deleteMany(entityName: string, ids: string[], permanent?: boolean): Promise<any>

Delete multiple records by IDs.

import { MagentrixError } from '@magentrix-corp/magentrix-sdk'

try {
  await dataService.deleteMany('Contact', [
    '00300000000001A0001',
    '00300000000001B0001',
    '00300000000001C0001'
  ])
  console.log('Contacts deleted successfully')
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Delete many failed:', error.message)
  }
}

Parameters:

  • entityName: Name of the entity
  • ids: Array of record IDs to delete
  • permanent (optional): If true, permanently deletes the records (default: false)

Returns: Deletion result

Throws: MagentrixError if entityName or ids is missing/empty


User Information

getUserInfo(): Promise<UserInfo>

Get information about the currently authenticated user.

import { MagentrixError, type UserInfo } from '@magentrix-corp/magentrix-sdk'

try {
  const userInfo: UserInfo = await dataService.getUserInfo()
  console.log('User Name:', userInfo.name)
  console.log('Username:', userInfo.userName)
  console.log('User ID:', userInfo.id)
  console.log('Role Type:', userInfo.roleType)
  console.log('Locale:', userInfo.locale)
  console.log('Preferred Currency:', userInfo.preferred_currency)
  console.log('Currency Symbol:', userInfo.userCurrencySymbol)
  console.log('Timezone Offset:', userInfo.user_timezone)
  console.log('Is Guest:', userInfo.guest)
  console.log('Is Impersonating:', userInfo.impr)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Failed to get user info:', error.message)
  }
}

Returns: UserInfo object containing:

  • name: Full name of the user
  • userName: Username of the user
  • id: User ID
  • guest: Whether the user is a guest
  • impr: Whether the user is using delegated access (impersonation)
  • preferred_currency: User's preferred currency ISO code
  • user_timezone: User's timezone offset
  • userCurrencySymbol: User's currency symbol
  • lang: User's language code
  • roleType: User's role type ('guest', 'employee', 'customer', 'partner', or 'admin')
  • locale: User's locale
  • display_user_currency: Whether to display amounts in user's currency

Throws: MagentrixError if the request fails


Custom Endpoints

execute(path: string, model?: any, method?: RequestMethod): Promise<any>

Execute a custom API endpoint.

import { MagentrixError, RequestMethod } from '@magentrix-corp/magentrix-sdk'

try {
  // GET request
  const data = await dataService.execute('/custom/endpoint', null, RequestMethod.get)
  console.log('GET result:', data)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('GET request failed:', error.message)
  }
}

try {
  // POST request
  const result = await dataService.execute('/custom/action', {
    param1: 'value1',
    param2: 'value2'
  }, RequestMethod.post)
  console.log('POST result:', result)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('POST request failed:', error.message)
  }
}

Parameters:

  • path: API endpoint path
  • model (optional): Request body data
  • method (optional): HTTP method (default: RequestMethod.post)

Returns: API response

Throws: MagentrixError if path is missing or GET request has a body


Error Handling

The SDK provides two custom error classes:

MagentrixError

General SDK errors (authentication, validation, API errors).

import { MagentrixError } from '@magentrix-corp/magentrix-sdk'

try {
  const result = await dataService.query('SELECT Id FROM Account')
  console.log(result.data) // Array of account objects
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Magentrix Error:', error.message)
  }
}

DatabaseError

Database-specific errors with detailed error information.

import { DatabaseError } from '@magentrix-corp/magentrix-sdk'

try {
  await dataService.create('Account', invalidData)
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Database Error:', error.message)
    if (error.hasErrors()) {
      error.getErrors().forEach(err => {
        console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
      })
    }
  }
}

Common Error Codes

The API returns specific error codes for different scenarios. Here are the most common ones:

Create Operation Errors

HTTP 406 Not Acceptable - Validation errors

{
  "errors": [
    {
      "code": "Missing_Field",
      "fieldName": "Name",
      "message": "You must enter a value."
    }
  ],
  "id": null,
  "success": false
}

HTTP 413 Request Entity Too Large - Payload exceeds size limit

{
  "errors": [
    {
      "code": "PAYLOAD_TOO_LARGE",
      "message": "The payload size exceeds the 20MB size limit."
    }
  ],
  "id": null,
  "success": false
}

HTTP 400 Bad Request - Missing or invalid payload

{
  "errors": [
    {
      "code": "PAYLOAD_MISSING",
      "message": "Request body is empty. A valid JSON/XML payload is required."
    }
  ],
  "id": null,
  "success": false
}

Update Operation Errors

HTTP 406 Not Acceptable - Validation errors

{
  "errors": [
    {
      "code": "Missing_Field",
      "fieldName": "LastName",
      "message": "You must enter a value."
    }
  ],
  "id": null,
  "success": false
}

HTTP 404 Not Found - Record not found

{
  "errors": [
    {
      "code": "MISSING_ENTITY",
      "message": "Record no longer exists."
    }
  ],
  "id": null,
  "success": false
}

HTTP 400 Bad Request - ID mismatch

{
  "errors": [
    {
      "code": "ENTITY_ID_MISMATCH",
      "message": "The ID in the request body does not match the record ID in the URL."
    }
  ],
  "id": null,
  "success": false
}

Delete Operation Errors

HTTP 406 Not Acceptable - Resource not found

{
  "message": "Resource not found",
  "success": false
}

HTTP 404 Not Found - Record not found

{
  "errors": [
    {
      "code": "ENTITY_NOT_FOUND",
      "message": "Record was not found or you may not have access."
    }
  ],
  "id": "Not found",
  "success": false
}

Authentication Errors

HTTP 401 Unauthorized - Invalid or expired session

{
  "message": "Session expired. Please authenticate again.",
  "success": false
}

HTTP 403 Forbidden - Invalid token or too many failed attempts

{
  "errors": [
    {
      "code": "403",
      "message": "Invalid Token"
    }
  ],
  "success": false
}

General Errors

HTTP 404 Not Found - Invalid entity or resource

{
  "errors": [
    {
      "code": "INVALID_ENTITY",
      "message": "Entity 'InvalidEntity' does not exist."
    }
  ],
  "id": null,
  "success": false
}

HTTP 500 Internal Server Error - Unexpected server error

{
  "message": "An unexpected error occurred.",
  "success": false
}

Error Handling Example

import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'

try {
  const newAccount = await dataService.create('Account', {
    Name: 'Acme Corporation',
    Email: '[email protected]'
  })
  console.log('Created:', newAccount.Id)
} catch (error) {
  if (error instanceof DatabaseError) {
    // Handle validation errors with field-level details
    console.error('Validation failed:', error.message)
    error.getErrors().forEach(err => {
      console.error(`- ${err.fieldName}: ${err.message} (Code: ${err.code})`)
    })
  } else if (error instanceof MagentrixError) {
    // Handle general API errors
    console.error('API Error:', error.message)
  } else {
    // Handle unexpected errors
    console.error('Unexpected error:', error)
  }
}

Advanced Usage

Automatic Session Management

The SDK automatically handles session creation and refresh:

import { MagentrixClient, MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: 'your-refresh-token',
  isDevMode: true
}

const dataService = new MagentrixClient(config)

// No need to call createSession() - the SDK handles it automatically
try {
  const result = await dataService.query('SELECT Id FROM Account')
  console.log(result.data) // Array of account objects
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

TypeScript Types

Import types for better type safety:

import {
  MagentrixClient,
  MagentrixConfig,
  SessionInfo,
  UserInfo,
  MagentrixError,
  DatabaseError,
  RequestMethod,
  ContentType
} from '@magentrix-corp/magentrix-sdk'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: 'your-refresh-token',
  isDevMode: true
}

const dataService = new MagentrixClient(config)

// Use UserInfo type for type safety
const userInfo: UserInfo = await dataService.getUserInfo()
console.log(`Welcome ${userInfo.name}!`)

Batch Operations

The create(), edit(), and upsert() methods accept arrays for efficient batch operations in a single API call.

✅ RECOMMENDED: Single API call with array

import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'

// Create multiple records in a single API call (OPTIMIZED)
const accounts = [
  { Name: 'Account 1', Email: '[email protected]', Status: 'Active' },
  { Name: 'Account 2', Email: '[email protected]', Status: 'Active' },
  { Name: 'Account 3', Email: '[email protected]', Status: 'Active' }
]

try {
  const created = await dataService.create('Account', accounts)
  console.log('Created IDs:', created.map(a => a.Id))
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Batch create failed:', error.message)
    error.getErrors().forEach(err => {
      console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
    })
  }
}

// Update multiple records in a single API call (OPTIMIZED)
try {
  const updates = [
    { Id: '00I00000000003x0001', Name: 'Updated Account 1', Status: 'Active' },
    { Id: '00I00000000003y0001', Name: 'Updated Account 2', Status: 'Inactive' },
    { Id: '00I00000000003z0001', Name: 'Updated Account 3', Status: 'Active' }
  ]
  const updated = await dataService.edit('Account', updates)
  console.log('Updated:', updated.length, 'records')
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Batch update failed:', error.message)
  }
}

// Upsert multiple records in a single API call (OPTIMIZED)
try {
  const records = [
    { Id: '00300000000001A0001', Name: 'John Doe', Email: '[email protected]' }, // Updates
    { Name: 'Jane Smith', Email: '[email protected]' }, // Creates (no Id)
    { Id: '00300000000001B0001', Name: 'Bob Johnson', Email: '[email protected]' } // Updates
  ]
  const results = await dataService.upsert('Contact', records)
  console.log('Upserted:', results.length, 'records')
} catch (error) {
  if (error instanceof DatabaseError) {
    console.error('Batch upsert failed:', error.message)
  }
}

// Delete multiple records
try {
  const idsToDelete = [
    '00I00000000003x0001',
    '00I00000000003y0001',
    '00I00000000003z0001'
  ]
  await dataService.deleteMany('Account', idsToDelete)
  console.log('Batch delete successful')
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Batch delete failed:', error.message)
  }
}

❌ NOT RECOMMENDED: Multiple API calls

// This makes multiple API calls - NOT optimized!
const accounts = [
  { Name: 'Account 1', Status: 'Active' },
  { Name: 'Account 2', Status: 'Active' },
  { Name: 'Account 3', Status: 'Active' }
]

// DON'T DO THIS - makes 3 separate API calls
const created = await Promise.all(
  accounts.map(account => dataService.create('Account', account))
)

// INSTEAD DO THIS - makes 1 API call
const created = await dataService.create('Account', accounts)

Custom Query Examples

import { MagentrixError } from '@magentrix-corp/magentrix-sdk'

try {
  // Simple query - returns array of records in 'data' property
  const result = await dataService.query(
    'SELECT Id, Name, Email FROM Contact WHERE Status = "Active"'
  )
  console.log('Active contacts:', result.data)

  // Iterate through results
  result.data.forEach(contact => {
    console.log(`${contact.Name} - ${contact.Email}`)
  })
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

try {
  // Query with sorting
  const result = await dataService.query(
    'SELECT Id, Name FROM Account ORDER BY Name ASC'
  )
  console.log('Sorted accounts:', result.data)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

try {
  // Query with limit
  const result = await dataService.query(
    'SELECT Id, Name FROM Account LIMIT 10'
  )
  console.log('Recent records:', result.data)
  console.log('Total records returned:', result.data.length)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

try {
  // Aggregate query - returns object with aggregate values
  const result = await dataService.query(
    'SELECT COUNT(Id) as TotalAccounts FROM Account'
  )
  console.log('Total accounts:', result.data.TotalAccounts)
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

try {
  // Multiple aggregates
  const result = await dataService.query(`
    SELECT
      COUNT(Id) as Total,
      SUM(AnnualRevenue) as Revenue,
      AVG(NumberOfEmployees) as AvgEmployees
    FROM Account
    WHERE Status = "Active"
  `)
  console.log('Statistics:', {
    total: result.data.Total,
    revenue: result.data.Revenue,
    avgEmployees: result.data.AvgEmployees
  })
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

Vue 3 Integration

Quick Start with Project Template

The fastest way to get started with a Vue.js project using the Magentrix SDK is to use the official project template:

npm create @magentrix-corp/iris-app-template@latest my-app
cd my-app
npm install
npm run dev

This template provides:

  • ✅ Pre-configured Magentrix SDK integration
  • ✅ Vue 3 + TypeScript setup
  • ✅ Vite for fast development
  • ✅ Example components and best practices
  • ✅ Ready-to-use authentication flow

Learn more: https://www.npmjs.com/package/@magentrix-corp/create-iris-app-template


Composable Usage

The SDK provides a dedicated Vue 3 composable:

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
import { useMagentrixSdk } from '@magentrix-corp/magentrix-sdk/vue'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: '<your-refresh-token>',
  isDevMode: true
}

const dataService = useMagentrixSdk().getInstance(config)
const accounts = ref<any[]>([])
const loading = ref(false)
const error = ref<string | null>(null)

const loadAccounts = async () => {
  loading.value = true
  error.value = null

  try {
    // Session is automatically created when needed
    const result = await dataService.query('SELECT Id, Name FROM Account')
    accounts.value = result.data // Extract the data array
  } catch (err) {
    if (err instanceof MagentrixError) {
      error.value = err.message
      console.error('Failed to load accounts:', err.message)
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadAccounts()
})
</script>

<template>
  <div>
    <div v-if="loading">Loading...</div>
    <div v-else-if="error">Error: {{ error }}</div>
    <ul v-else>
      <li v-for="account in accounts" :key="account.Id">
        {{ account.Name }}
      </li>
    </ul>
  </div>
</template>

Reactive CRUD Operations

<script setup lang="ts">
import { ref } from 'vue'
import { MagentrixError, DatabaseError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
import { useMagentrixSdk } from '@magentrix-corp/magentrix-sdk/vue'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: '<your-refresh-token>',
  isDevMode: true
}

const dataService = useMagentrixSdk().getInstance(config)

const formData = ref({
  Name: 'Company Name',
  Type: 'Customer',
  Status: 'Active'
})

const createAccount = async () => {
  try {
    const created = await dataService.create('Account', formData.value)
    console.log('Created:', created)

    // Reset form
    formData.value = { Name: '', Type: '', Status: 'Active' }
  } catch (error) {
    if (error instanceof DatabaseError) {
      console.error('Database error:', error.message)
      error.getErrors().forEach(err => {
        console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
      })
    } else if (error instanceof MagentrixError) {
      console.error('Failed to create account:', error.message)
    }
  }
}

const updateAccount = async (id: string) => {
  try {
    await dataService.edit('Account', {
      Id: id,
      ...formData.value
    })
    console.log('Updated successfully')
  } catch (error) {
    if (error instanceof DatabaseError) {
      console.error('Database error:', error.message)
      error.getErrors().forEach(err => {
        console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
      })
    } else if (error instanceof MagentrixError) {
      console.error('Failed to update account:', error.message)
    }
  }
}

const deleteAccount = async (id: string) => {
  try {
    await dataService.delete('Account', id)
    console.log('Deleted successfully')
  } catch (error) {
    if (error instanceof MagentrixError) {
      console.error('Failed to delete account:', error.message)
    }
  }
}
</script>

Best Practices

1. Environment-Specific Configuration

Use environment variables for configuration:

const dataService = new MagentrixClient({
  baseUrl: process.env.MAGENTRIX_BASE_URL || 'https://your-portal-domain.com',
  refreshToken: process.env.MAGENTRIX_REFRESH_TOKEN,
  isDevMode: process.env.NODE_ENV === 'development'
})

2. Error Handling

Always handle errors appropriately:

import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'

try {
  const result = await dataService.create('Account', data)
  console.log('Account created:', result.Id)
} catch (error) {
  if (error instanceof DatabaseError) {
    // Handle database validation errors
    console.error('Database Error:', error.message)
    error.getErrors().forEach(err => {
      console.error(`${err.fieldName}: ${err.message}`)
    })
  } else if (error instanceof MagentrixError) {
    // Handle general SDK errors
    console.error('SDK Error:', error.message)
  } else {
    // Handle unexpected errors
    console.error('Unexpected error:', error)
  }
}

3. Session Management

The SDK automatically manages sessions - no manual initialization needed:

// app.ts or main.ts
import { MagentrixClient, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: 'your-refresh-token',
  isDevMode: true
}

const dataService = new MagentrixClient(config)

// No need to call createSession() - it's handled automatically
// Export for use throughout the app
export { dataService }

4. Production Deployment

For production (cookie-based auth), no session creation needed:

import { MagentrixClient, MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  isDevMode: false // Uses ASP.NET session cookies
}

const dataService = new MagentrixClient(config)

// No need to call createSession()
// Just use the dataService directly
try {
  const result = await dataService.query('SELECT Id FROM Account')
  console.log(result.data) // Array of account objects
} catch (error) {
  if (error instanceof MagentrixError) {
    console.error('Query failed:', error.message)
  }
}

Troubleshooting

Common Issues

Issue: Session expired and no refresh token available

Solution: Ensure refreshToken is provided in config when using isDevMode: true

import { MagentrixClient, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'

const config: MagentrixConfig = {
  baseUrl: 'https://your-portal-domain.com',
  refreshToken: 'your-refresh-token', // Required for dev mode
  isDevMode: true
}

const dataService = new MagentrixClient(config)

Issue: Login failed error when creating session

Solution: Verify that your refresh token is valid and not expired. Refresh tokens can be obtained from your Magentrix instance.


Issue: Redirected to login page in production

Solution: This is expected behavior when using isDevMode: false. The SDK automatically detects session expiration and redirects to the login page. Ensure users are authenticated via ASP.NET Forms Authentication.


License

Proprietary

Support

For issues and questions:

  • Documentation: [Magentrix Help Center]https://help.magentrix.com/
  • Website: Magentrix.com

Changelog

1.0.0

  • Initial release
  • Token-based and cookie-based authentication
  • CRUD operations
  • Custom queries
  • Vue 3 composable
  • TypeScript support
  • Automatic session management