apptree-mobile
v0.5.1
Published
TypeScript SDK for building connectors that integrate with the AppTree platform. Provides GraphQL access, data upload/sync methods, request tracing, and Cloud Task queue management.
Readme
AppTree Graph SDK (apptree-mobile)
TypeScript SDK for building connectors that integrate with the AppTree platform. Provides GraphQL access, data upload/sync methods, request tracing, and Cloud Task queue management.
Installation
yarn add apptree-mobileRegenerating the GraphQL client
generate-graphql-client -s ../firebase_functions/functions/graphql.schema.json -o src/apptreeQuick Start
import { Service } from 'apptree-mobile';
const apptree = new Service({
project: 'my-app',
secret: process.env.APPTREE_API_KEY,
});
// GraphQL queries
const user = await apptree.query
.user({ username: 'jsmith' })
.execute({ session: { access_token: true } });
// GraphQL mutations
await apptree.mutate
.updateUser({ username: 'jsmith', updates: { userUpdates: { data: userData } } })
.execute({ username: true });Service Constructor
const apptree = new Service({
project: 'my-app', // App/project identifier
secret: process.env.API_KEY, // API key or project:secret combo
host: 'https://api.apptree.io', // Optional, defaults to production
defaultTraceDetail: 'standard', // Optional, 'standard' or 'verbose'
taskQueueManager: tqm, // Optional, enables queue features
});Data Upload
Upload a collection (bulk replace or append)
await apptree.uploadCollection({
collectionId: 'my_work_orders',
data: workOrders,
pkField: 'wopk',
username: 'jsmith',
append: false, // true to append, false to replace
traceId: 'trace-id', // optional
});Append to a collection
await apptree.appendToCollection({
collectionId: 'my_work_orders',
data: newRecords,
pkField: 'wopk',
username: 'jsmith',
traceId: 'trace-id', // optional
});Upload a list
await apptree.uploadList({
listId: 'failure_codes',
data: codes,
username: 'jsmith', // omit for app-scoped lists
traceId: 'trace-id', // optional
});Request Tracing
The platform sends a trace ID with every request to your connector via the X-Trace-Id header. By participating in this trace, you create an end-to-end view of how data flows from the client through the platform, into your connector, out to external APIs, and back.
Tracing is always optional and fire-and-forget. If the trace system is unavailable or you choose not to trace, nothing breaks.
When to use manual tracing
Use manual tracing when your connector handles requests directly — webhook endpoints, form submissions, search handlers, or any controller method where you control the code that runs. Manual tracing gives you full control over what gets recorded.
Common scenarios:
- Tracing an external API call to understand latency
- Recording a data transformation step
- Tracking error details when a request fails
- Adding business context (e.g., "fetched 200 work orders matching filter X")
When to use automated tracing
Use the automated sync methods (syncCollection, syncList) when you're doing paginated data fetching. These methods handle tracing internally — recording the overall sync duration, and optionally per-page timing when verbose tracing is enabled. You don't need to add manual trace calls inside the sync flow.
Manual Tracing
Step 1: Parse the trace context
Every request from the platform includes trace headers. Use TraceHelper to extract them:
import { TraceHelper } from 'apptree-mobile';
app.post('/work_order/collection', async (req, res) => {
const traceInfo = TraceHelper.fromRequest(req);
// traceInfo: { traceId, parentSpanId?, appId?, userId? }
// Returns null if no X-Trace-Id header is present
});TraceHelper.fromRequest checks two sources for the trace ID:
- The
X-Trace-Idheader (set by the platform on direct webhook calls) - The
traceIdfield in the request body (present on Cloud Task continuations where headers aren't forwarded)
It also reads X-Parent-Span-Id from headers, and app and username from the request body to build appId and userId. The userId is formatted as {app}_{username} to match platform conventions.
Step 2: Record trace events
Use recordTrace to record individual events. Each call sends a single span to the platform. No batching, no persistent state.
const start = Date.now();
const workOrders = await externalApi.fetchWorkOrders(filters);
if (traceInfo) {
await apptree.recordTrace({
...traceInfo,
operation: 'RefreshCollection',
step: 'fetch-from-external-api',
status: 'success',
durationMs: Date.now() - start,
metadata: { count: workOrders.length, filters },
});
}Always guard trace calls with if (traceInfo) so your connector works correctly when no trace headers are present (e.g., during local development or from older platform versions).
recordTrace fields
| Field | Required | Description |
|-------|----------|-------------|
| traceId | yes | Trace ID from TraceHelper |
| operation | yes | What the connector is doing (e.g., 'RefreshCollection', 'SearchWorkOrders') |
| step | yes | Which part of the operation (e.g., 'fetch-from-external-api', 'transform-data', 'complete') |
| status | yes | 'success', 'error', or 'in_progress' |
| parentSpanId | no | Parent span from TraceHelper |
| appId | no | App ID from TraceHelper |
| userId | no | User ID from TraceHelper |
| durationMs | no | How long this step took in milliseconds |
| metadata | no | Any additional context (record counts, filter values, etc.) |
| error | no | Error message when status is 'error' |
| request | no | Request data for debugging |
| response | no | Response data for debugging |
recordTrace never throws. If the trace API is unreachable, the call silently succeeds.
Step 3: Pass the trace ID through uploads
When uploading data, include the traceId so the platform can link the upload to the originating trace:
await apptree.uploadCollection({
collectionId: 'my_work_orders',
data: workOrders,
pkField: 'wopk',
username: 'jsmith',
traceId: traceInfo?.traceId,
});Full manual tracing example
import { TraceHelper } from 'apptree-mobile';
app.post('/work_order/collection', async (req, res) => {
const traceInfo = TraceHelper.fromRequest(req);
const apptree = await useAppTreeService(req.body.app);
const username = req.body.username;
// Trace: start
if (traceInfo) {
await apptree.recordTrace({
...traceInfo,
operation: 'RefreshCollection',
step: 'start',
status: 'in_progress',
metadata: { collection: 'my_work_orders', username },
});
}
// Fetch from external API
const fetchStart = Date.now();
const workOrders = await externalApi.fetchWorkOrders();
if (traceInfo) {
await apptree.recordTrace({
...traceInfo,
operation: 'RefreshCollection',
step: 'fetch-from-external-api',
status: 'success',
durationMs: Date.now() - fetchStart,
metadata: { count: workOrders.length },
});
}
// Upload with trace linkage
await apptree.uploadCollection({
collectionId: 'my_work_orders',
data: workOrders,
pkField: 'wopk',
username,
traceId: traceInfo?.traceId,
});
// Trace: complete
if (traceInfo) {
await apptree.recordTrace({
...traceInfo,
operation: 'RefreshCollection',
step: 'complete',
status: 'success',
});
}
res.sendStatus(200);
});Tracing across Cloud Task continuations
When your connector uses Cloud Tasks for pagination, the trace ID needs to survive across task boundaries. Cloud Tasks don't forward HTTP headers, so the trace ID must travel in the request body.
If you're using FetchInfo with CollectionDataFetcher, add traceId to the FetchInfo object:
const fetchInfo: FetchInfo<MyContext> = {
context: { filters },
collection: 'my_work_orders',
username,
app,
// ... other fields
traceId: traceInfo?.traceId, // survives across task continuations
};TraceHelper.fromRequest automatically checks req.body.traceId as a fallback when no X-Trace-Id header is present, so the trace context is recovered on the continuation endpoint without extra work.
Automated Tracing with Sync Methods
The syncCollection and syncList methods handle pagination and tracing internally. Pass a traceId and they record spans automatically.
syncCollection
Fetches pages of data from an external API and uploads them to a collection one page at a time. Manages loading state, handles search cancellation, and records trace spans.
const traceInfo = TraceHelper.fromRequest(req);
await apptree.syncCollection({
collectionId: 'my_work_orders',
username: 'jsmith',
pkField: 'wopk',
traceId: traceInfo?.traceId,
traceDetail: 'standard', // or 'verbose' for per-page spans
searchId: req.body.searchId, // optional, enables cancellation detection
onBeforeSync: async () => {
// Runs after loading:true, before first page fetch.
// Use for custom setup like setting a query message for the user.
await apptree.mutate.updateUserCollectionInfo({
username: 'jsmith',
collectionId: 'my_work_orders',
updates: { customData: { queryMessage: 'Filtering by: Status = Open' } },
}).execute({ success: true });
},
fetchPage: async (cursor) => {
const offset = cursor ?? 0;
const res = await externalApi.getWorkOrders({ offset, pageSize: 100 });
return {
data: res.items.map(transformWorkOrder),
nextCursor: res.hasNextPage ? offset + 100 : null,
};
},
onProgress: ({ uploaded, pageNumber }) => {
console.log(`Page ${pageNumber}: ${uploaded} records uploaded`);
},
});What syncCollection does internally:
- Sets
loading: trueon the collection - Calls
onBeforeSyncif provided - Fetches upload URLs from
collectionInfo - Loops: calls your
fetchPage, uploads each page (first page = bulk replace, subsequent pages = append) - Before each page after the first, checks
searchId— if the user started a new search, stops without settingloading: false(the new search owns the loading state) - Sets
loading: falsewhen pagination completes normally - Records a trace span summarizing the sync
Search cancellation: When searchId is provided, the SDK queries the collection's current searchId before fetching each page (starting from page 2). If the searchId has changed, it means the user initiated a new search — pagination stops immediately. The loading state is left as-is because the new search is still running. Even though data from earlier pages was already uploaded, the platform's ingestion layer will discard it if the searchId doesn't match.
Error handling: If fetchPage or onBeforeSync throws, the SDK sets loading: false, records an error trace span, and re-throws the error to your code.
syncList
Fetches pages of data and accumulates them in memory, then uploads the complete dataset as a single list upload.
const traceInfo = TraceHelper.fromRequest(req);
await apptree.syncList({
listId: 'failure_codes',
username: 'jsmith', // omit for app-scoped lists
traceId: traceInfo?.traceId,
traceDetail: 'standard',
fetchPage: async (cursor) => {
const offset = cursor ?? 0;
const res = await externalApi.getFailureCodes({ offset });
return {
data: res.items,
nextCursor: res.hasNextPage ? offset + res.pageSize : null,
};
},
});What syncList does internally:
- Loops: calls your
fetchPage, accumulates all records in memory - When pagination is complete, uploads all data at once via
uploadList - Records a trace span summarizing the sync
- If
fetchPagethrows mid-pagination, no partial data is uploaded
Unlike syncCollection, lists don't have loading state or search cancellation. The entire dataset is fetched then uploaded atomically.
Trace detail levels
Both syncCollection and syncList support two trace detail levels:
| Level | What's recorded |
|-------|----------------|
| 'standard' | One span when the sync completes: total pages, total records, duration, and status |
| 'verbose' | Everything in standard, plus a span per page with individual page timing and record counts |
Set the default on the Service constructor via defaultTraceDetail, or override per call with the traceDetail option. Use 'verbose' when debugging slow syncs or investigating page-level issues.
Background List Queuing with queueSyncList
For background list uploads (e.g., refreshing expired lists during user login), use queueSyncList to dispatch the work to a Cloud Task queue. This returns immediately — the actual sync runs later when the task fires.
Setup
Create a TaskQueueManager and pass it to the Service:
import { Service, TaskQueueManager } from 'apptree-mobile';
const taskQueueManager = new TaskQueueManager({
connectorHost: process.env.SERVICE_URL,
connectorName: 'maintenance-connection',
queues: {
normal: { maxConcurrency: 10 },
background: { maxConcurrency: 5 },
},
});
// Auto-creates queues on startup (idempotent)
await taskQueueManager.initialize();
const apptree = new Service({
project: 'my-app',
secret: process.env.API_KEY,
taskQueueManager,
});Queue names are generated as {connectorName}-{priority} (e.g., maintenance-connection-background). The maxConcurrency controls how many tasks can run simultaneously in each queue.
The connector's Cloud Run service account needs cloudtasks.queues.create and cloudtasks.tasks.create IAM permissions. Authentication uses Application Default Credentials — no key files needed on Cloud Run.
Dispatching a list sync
await apptree.queueSyncList({
listId: 'failure_codes',
username: 'jsmith', // omit for app-scoped lists
priority: 'background', // 'high', 'normal', or 'background'
callbackPath: '/lists/upload/failure_codes',
callbackBody: { app: 'my-app' },
traceId: traceInfo?.traceId,
});This creates a Cloud Task that will POST to {connectorHost}/lists/upload/failure_codes with the list info in the body. Your callback endpoint receives the task and runs syncList:
app.post('/lists/upload/failure_codes', async (req, res) => {
const traceInfo = TraceHelper.fromRequest(req);
const apptree = await useAppTreeService(req.body.app);
await apptree.syncList({
listId: req.body.listId,
username: req.body.username,
traceId: traceInfo?.traceId ?? req.body.traceId,
fetchPage: async (cursor) => { /* ... */ },
});
res.sendStatus(200);
});Error behavior
queueSyncList throws immediately if:
TaskQueueManagerwas not provided to theServiceconstructorTaskQueueManager.initialize()was not called or failed- The requested priority level has no queue configured
Without a TaskQueueManager, syncCollection and syncList still work normally (in-process). Queue features are opt-in.
GraphQL Access
The Service exposes typed GraphQL query and mutation chains:
// Queries
const info = await apptree.query
.collectionInfo({ username: 'jsmith', collectionId: 'my_work_orders' })
.execute({ bulkUploadUrl: true, appendUploadUrl: true, searchId: true });
// Mutations
await apptree.mutate
.updateUserCollectionInfo({
username: 'jsmith',
collectionId: 'my_work_orders',
updates: { loading: true },
})
.execute({ success: true });The execute call accepts a request object specifying which fields to return. Only requested fields are included in the GraphQL query.
Request Types
The SDK exports typed request interfaces matching the webhook payloads sent by the platform:
| Interface | Used For |
|-----------|----------|
| HookRequest | Base type with app, username, state |
| RefreshCollectionRequest | Collection refresh webhooks |
| SearchRequest | Collection search webhooks |
| FormSubmissionRequest | Form submission webhooks |
| SearchListRequest | List search webhooks |
