All documentation
Documentation
Copy the code below into updateSchedules.ts in your server application. It uses native fetch and runs on Node.js 18 or later. The client returns the contents of the API’s data field and exposes HTTP errors through ScheduleApiError.
Use the update schedules reference for authentication, examples, and write preconditions.
/** Server-side TypeScript client for Grade SDK v1. Requires native fetch (Node 18+). */
export type SchedulePlatform = 'instagram' | 'tiktok' | 'youtube' | 'facebook' | 'twitter';
export type ScheduleStatus = 'OFF' | 'ON';
export type ScheduleAlert = {
type: 'alert';
to: 'slack' | 'discord' | 'webhook';
message: 'post_uploaded' | 'post_taking_off' | 'latest_numbers';
once_per_post: boolean;
};
export type UpdateNow = { type: 'check_now' };
export type ScheduleCondition = {
type: 'if';
metric: 'views' | 'likes' | 'comments' | 'shares';
reaches: number;
compared_with: 'fixed_number' | 'creator_usual_first_day';
then: (ScheduleAlert | UpdateNow)[];
};
export type ScheduleTimer = {
type: 'check';
every_minutes: number;
for_hours: number;
on_each_check: (ScheduleAlert | ScheduleCondition)[];
};
type BaseBody = {
schema: 'check-rule/v1';
name: string;
budget: { monthly_usd: number; when_reached: 'daily_check_only' };
};
export type ScheduleBody = BaseBody &
(
| {
when: { event: 'post_uploaded'; platforms: SchedulePlatform[]; find_within_minutes: number };
steps: (ScheduleAlert | ScheduleTimer | UpdateNow)[];
}
| {
when: {
event: 'schedule';
timezone: string;
platforms: SchedulePlatform[];
uploaded_within_days?: number;
} & ({ times: string[]; every_hours?: never } | { every_hours: number; times?: never });
}
);
export type ScheduleRow = {
id: string;
name: string;
kind: 'post_uploaded' | 'schedule';
campaign: { id: string; name: string } | null;
status: ScheduleStatus;
version: number;
body: ScheduleBody | null;
turnedOnAt: string | null;
updatedAt: string;
thisMonth: { postUpdates: number; accountUpdates: number; costUsd: number };
pausedToday: { reason: 'RULE_LIMIT' | 'DAILY_CAP' | 'BALANCE'; count: number; lastAt: string } | null;
};
export type DailyLimit = { limit: number; postUpdatesToday: number; min: number; max: number };
export type ScheduleOverview = {
asOf: string;
running: boolean;
pricePerUpdateUsd: number;
dailyLimit: DailyLimit;
schedules: ScheduleRow[];
billing: {
chargedThisMonthUsd: number;
notChargedYetUsd: number;
lastChargedDay: string | null;
pausedForBalance: { since: string } | null;
} | null;
};
export type ScheduleIssue = { path: string; message: string };
export type ScheduleEstimate = {
asOf: string;
issues: ScheduleIssue[];
postsInScope: number | null;
newPostsPerMonth: number | null;
accountsInScope: number | null;
perDay: { postUpdates: number; accountUpdates: number; overDailyLimit: number };
perMonth: {
postUpdates: number;
accountUpdates: number;
alerts: number | null;
costUsd: number;
costWithoutLimitsUsd: number;
monthlyLimitReachedOnDay: number | null;
};
parts: { path: string; label: string; updatesPerMonth: number; costUsd: number }[];
notes: string[];
};
export type ScopeAndBody = { campaignId: string | null; body: ScheduleBody };
export type ScheduleEstimateInput = ({ checkRuleId: string } | ScopeAndBody) & { dailyLimit?: number };
export type ReviewedSchedule = {
expectedVersion: number;
expectedStatus: ScheduleStatus;
expectedDailyLimit: number;
};
export type ScheduleTransition =
| ({ status: 'ON' } & ReviewedSchedule)
| { status: 'OFF'; expectedVersion: number; expectedStatus: ScheduleStatus; expectedDailyLimit?: number };
export type UpdateTarget = { mediaType: 'CCM' | 'ATM'; mediaId: string };
export type QueuedUpdate = UpdateTarget & {
updateId: string;
scheduleId: string;
version: number;
status: 'queued';
unitPriceUsd: number;
currency: 'USD';
queuedAt: string;
};
export type UpdateReceipt = Omit<QueuedUpdate, 'status'> & {
status: 'queued' | 'dispatching' | 'awaiting_settlement' | 'provider_accepted' | 'settled_without_run';
billing: {
status: 'reserved' | 'billable' | 'settled' | 'settled_without_charge';
billableUsd: number;
chargeId: string | null;
settledAt: string | null;
};
};
export type ScheduleErrorDetails = {
success?: false;
message?: string;
code?: string;
field?: string;
errors?: ScheduleIssue[];
};
export class ScheduleApiError extends Error {
readonly status: number;
readonly details: ScheduleErrorDetails;
readonly retryAfter: string | null;
constructor(status: number, details: ScheduleErrorDetails, retryAfter: string | null) {
super(details.message || `Grade returned HTTP ${status}.`);
this.name = 'ScheduleApiError';
this.status = status;
this.details = details;
this.retryAfter = retryAfter;
}
}
export function createUpdateSchedulesClient(config: {
baseUrl: string;
applicationId: string;
apiKey: string;
fetch?: typeof fetch;
}) {
const base = new URL(config.baseUrl);
if (
base.search ||
base.hash ||
base.username ||
base.password ||
!base.pathname.replace(/\/$/, '').endsWith('/sdk/v1')
) {
throw new TypeError('Use an SDK v1 base URL ending in /sdk/v1.');
}
const local = ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname);
if (base.protocol !== 'https:' && !(local && base.protocol === 'http:')) {
throw new TypeError('Use HTTPS or a loopback HTTP address for local development.');
}
if (!config.applicationId.trim() || !config.apiKey.trim())
throw new TypeError('Set the application ID and API key.');
base.pathname = base.pathname.replace(/\/$/, '') + '/update-schedules';
const fetchImpl = config.fetch ?? fetch;
async function request<T>(method: string, path: string, body?: unknown, key?: string): Promise<T> {
const headers = new Headers({
Accept: 'application/json',
'X-Application-Id': config.applicationId,
'X-Api-Key': config.apiKey,
});
if (body !== undefined) headers.set('Content-Type', 'application/json');
if (key !== undefined) headers.set('X-Idempotency-Key', key);
const response = await fetchImpl(base.href + path, {
method,
headers,
...(body === undefined ? {} : { body: JSON.stringify(body) }),
redirect: 'error',
signal: AbortSignal.timeout(15000),
});
const result = await response.json().catch(() => null);
if (!response.ok) {
throw new ScheduleApiError(
response.status,
result && typeof result === 'object' ? result : {},
response.headers.get('Retry-After'),
);
}
if (result?.success !== true || !Object.hasOwn(result, 'data') || result.data === null) {
throw new Error('Grade returned an invalid update-schedule response.');
}
return result.data as T;
}
function write<T>(method: 'POST' | 'PUT', path: string, body: unknown, key: string) {
if (typeof key !== 'string' || !/^[!-~]{1,100}$/.test(key))
throw new TypeError('Supply an idempotency key of 1–100 visible ASCII characters for this operation.');
return request<T>(method, path, body, key);
}
function idPath(id: string): string {
if (typeof id !== 'string' || !id.trim() || id === '.' || id === '..')
throw new TypeError('Supply a valid resource ID.');
return '/' + encodeURIComponent(id);
}
return {
overview: () => request<ScheduleOverview>('GET', ''),
get: (id: string) => request<ScheduleRow>('GET', idPath(id)),
estimate: (input: ScheduleEstimateInput) => request<ScheduleEstimate>('POST', '/estimate', input),
create: (input: ScopeAndBody, key: string) => write<ScheduleRow>('POST', '', input, key),
saveVersion: (id: string, input: ReviewedSchedule & { body: ScheduleBody }, key: string) =>
write<ScheduleRow>('POST', idPath(id) + '/versions', input, key),
setStatus: (id: string, input: ScheduleTransition, key: string) =>
write<ScheduleRow>('POST', idPath(id) + '/status', input, key),
requestUpdate: (id: string, input: UpdateTarget & { expectedVersion: number }, key: string) =>
write<QueuedUpdate>('POST', idPath(id) + '/updates', input, key),
getUpdate: (id: string, updateId: string) =>
request<UpdateReceipt>('GET', idPath(id) + '/updates' + idPath(updateId)),
setDailyLimit: (input: { dailyLimit: number; expectedDailyLimit: number }, key: string) =>
write<DailyLimit>('PUT', '/daily-limit', input, key),
};
}
