Skip to content
中文

Sync a web back office into a database on a schedule

Many back offices have no open API, but their web pages fetch JSON from endpoints of their own. This recipe has a saved script open the signed-in back-office page every day, call those endpoints from the page, merge the result into a database on a unique key, and write one record per run. It is layers ① ② ③ of the business operations hub.

The run on this page uses the platform’s own public docs search endpoint in place of a real back office: it opens a page on api.deepraxis.com, then requests the same-origin /meta/v1/docs/search from that page. For your back office, change two inputs only: the page address and the path of its list endpoint.

Prerequisites

  • An API key, plus Bash, curl and jq, as in step 1 of the automation quickstart.
  • Your back office: a page that shows a list after sign-in, and the list endpoint that page calls. Find it in the Network panel of your browser’s developer tools and note its path, paging parameters and field names.
  • Read and write only data in your own accounts; where the back office has an official open API, use the API.
终端窗口
export PRAXIS_API_URL="https://api.deepraxis.com"
: "${PRAXIS_API_KEY:?Set PRAXIS_API_KEY to your API Key}"
api() { curl --fail-with-body -sS "$PRAXIS_API_URL$1" -H "Authorization: Bearer $PRAXIS_API_KEY" -H 'Content-Type: application/json' "${@:2}"; }

1. Create the database and two tables

pages is the raw table: one row per source record, with path as the unique key. sync_runs is the run record: one row per sync. For your back office, give the raw table its fields and make the source id (order number, product id) unique.

终端窗口
DB=$(api /database/v1/table --data '{"name":"ops-hub"}' | jq -er .id)
api /database/v1/table/$DB/tables --data '{"name":"pages","fields":[
{"name":"path","type":"string","required":true,"unique":true},
{"name":"title","type":"string"},{"name":"url","type":"string"},{"name":"snippet","type":"string"},
{"name":"synced_at","type":"datetime","indexed":true}]}' | jq -e '.name == "pages"'
api /database/v1/table/$DB/tables --data '{"name":"sync_runs","fields":[
{"name":"run_id","type":"string","unique":true},{"name":"started_at","type":"datetime","indexed":true},
{"name":"finished_at","type":"datetime"},{"name":"status","type":"string"},
{"name":"rows","type":"integer"},{"name":"error","type":"string"}]}' | jq -e '.name == "sync_runs"'

Expected: true twice.

2. Create a sign-in context and complete the first sign-in

A context keeps cookies and localStorage, and the same context is reused every day.

终端窗口
CTX=$(api /browser/v1/contexts --data '{}' | jq -er .id)

A real back office needs a person for the first sign-in: open a session with this context, open the sign-in page, request a handoff, and the account holder enters the code or scans the QR code under Browser › Sessions in the Console; then complete the handoff and close the session. Create the session with browserSettings.context: {id: CTX, persist: true}, or the sign-in is not saved when the session closes. Signing in, verification codes and accepting terms are done by a person.

The stand-in target on this page is a public page and needs no sign-in, so the manual part of this step can be skipped.

3. Write the sync script

Save the following as sync.ts. It does five things in order: open a session with the context → open the back-office page → request the list endpoint from the page → release the session → merge the rows on the unique key and record the run.

type Input = {
database_id: string; // database the sync writes to
context_id: string; // context holding the back office sign-in
page: string; // back-office page opened after sign-in
list: string; // list endpoint the page itself calls (same-origin path)
};
type Row = { path: string; title: string; url: string; snippet: string };
export default async (input: Input): Promise<{ run_id: string; rows: number }> => {
const startedAt = new Date().toISOString();
const runId = `sync-${startedAt}`;
const db = (table: string) => ({ database_id: input.database_id, table });
let rows: Row[] = [];
let error: string | null = null;
// 1. Open a browser session with the saved sign-in; persist:true writes renewed cookies back.
const session = await praxis.browser.sessions.create({
body: { keepAlive: true, timeout: 600, browserSettings: { context: { id: input.context_id, persist: true } } },
});
try {
// 2. Open the back-office page, then call its own list endpoint from the page: the request carries the page's cookies.
await praxis.browser.sessions.actions.create({ path: { sessionId: session.id }, body: { type: "open", url: input.page } });
const result = await praxis.browser.sessions.actions.create({
path: { sessionId: session.id },
body: { type: "evaluate", expression: `fetch(${JSON.stringify(input.list)}).then(r => r.ok ? r.json() : Promise.reject(new Error("HTTP " + r.status)))` },
});
rows = (result as { value: Row[] }).value;
} catch (e) {
error = String(e);
} finally {
// 3. Release the session as soon as it is done, so billing stops.
await praxis.browser.sessions.update({ path: { sessionId: session.id }, body: { status: "REQUEST_RELEASE" } });
}
// 4. Merge on the unique key: a rerun writes no duplicate rows.
if (!error && rows.length > 0) {
await praxis.database.table.rest.create({
path: db("pages"),
query: { on_conflict: "path" },
headers: { Prefer: "resolution=merge-duplicates" },
body: rows.map((r) => ({ path: r.path, title: r.title, url: r.url, snippet: r.snippet, synced_at: startedAt })),
});
}
// 5. One run record per run; the steward and the report read it.
await praxis.database.table.rest.create({
path: db("sync_runs"),
body: { run_id: runId, started_at: startedAt, finished_at: new Date().toISOString(), status: error ? "failed" : "succeeded", rows: rows.length, error },
});
if (error) throw new Error(error);
return { run_id: runId, rows: rows.length };
};

Why it is written this way:

  • The list endpoint is requested from the page with evaluate, so the request carries the page’s cookies and you handle no signing yourself. An evaluate expression is at most 20000 characters, and one page action finishes within 30 seconds.
  • Rows are merged with on_conflict=path and Prefer: resolution=merge-duplicates: a rerun updates the same record instead of adding a row. Backfilling history is rerunning day by day.
  • A failure also writes a status: failed run record, then throws so the run fails. Checks read the run records instead of the logs.
  • The session is released in finally, so a failure does not keep it billing.

Validate first, then run it once. page is the back-office page address and list the path of the list endpoint that page calls:

终端窗口
api /automation/v1/validate --data "$(jq -n --rawfile source sync.ts '{kind:"script",source:$source}')" | jq -e '.valid'
INPUT=$(jq -n --arg db "$DB" --arg ctx "$CTX" '{database_id:$db, context_id:$ctx,
page:"https://api.deepraxis.com/meta/v1/health",
list:"/meta/v1/docs/search?q=%E6%95%B0%E6%8D%AE%E5%BA%93&limit=20&lang=zh"}')
api /automation/v1/runs --data "$(jq -n --rawfile source sync.ts --argjson input "$INPUT" \
'{source:$source, language:"ts", input:$input, wait:60}')" | jq '{status, output}'

Expected: status is completed and output.rows is the number of rows synced (19 in the run below). Run the same command again, then check there are no duplicates:

终端窗口
api "/database/v1/table/$DB/rest/pages?select=path" | jq '{rows: length, distinct: (map(.path) | unique | length)}'
api "/database/v1/table/$DB/rest/sync_runs?select=run_id,status,rows&order=started_at.asc"

Expected: rows equals distinct; sync_runs has two succeeded rows.

4. Save, publish and run it every day

终端窗口
NS="ops-hub"; NAME="sync-backoffice"
api /automation/v1/scripts --data "$(jq -n --arg ns $NS --arg n $NAME --rawfile s sync.ts '{namespace:$ns,name:$n,draft:{source:$s}}')" | jq -e '.id'
REV=$(api /automation/v1/scripts/$NS/$NAME | jq -er .draft.revision)
api /automation/v1/scripts/$NS/$NAME/versions --data "{\"version\":\"1.0.0\",\"draft\":{\"revision\":\"$REV\"}}" | jq -e '.version'
api /automation/v1/triggers --data "$(jq -n --arg t "$NS/$NAME@1.0.0" --argjson input "$INPUT" \
'{name:"daily sync", target:$t, kind:"schedule", schedule:{cron:"0 1 * * *"}, timezone:"Asia/Shanghai", input:$input}')" | jq '{id, state}'

Expected: the trigger’s state is enabled and it runs at 01:00 Beijing time every day. A trigger points at one version: after publishing a new script version, move the trigger’s target to it. To see a scheduled firing right away, add a one-off trigger with schedule: {at: "<UTC time two minutes from now>"} and check sync_runs after it fires.

5. Adapt it to your back office

  • Change the page and list inputs; when the list endpoint pages, loop over the pages inside the evaluate expression and return them once.
  • Change the Row type and the written fields to match the raw table; convert amounts to one unit and note the source unit in the field description.
  • Run one day by hand and check it cell by cell against a hand-made report before backfilling and scheduling.
  • When an account can be signed in in only one place, run every sync that uses its context one after another, never in parallel.

Troubleshooting

SymptomCause and fix
The run fails with HTTP 401 in sync_runs, or lands on the sign-in pageThe sign-in expired. Have the account holder sign in again as in step 2
The run fails with HTTP 404The list endpoint path changed. Find it again in the page’s Network panel and update the trigger’s input.list
409 CONTEXT_LOCKEDAnother session is writing the same context. Run the tasks that use it one after another
The result is cut off or slowevaluate returns too much at once. Request smaller pages; one action must finish within 30 seconds
More rows after a rerunNo unique key, or the write lacks on_conflict and merge-duplicates

Run record

2026-11-25, Develop. Stand-in back office: the docs search endpoint, query 「数据库」.

ItemResult
First runcompleted, 19 rows, about 7 seconds
Reruncompleted, still 19 rows with 19 distinct path values; synced_at moved to the second run
Failure branchlist set to a missing path: the run faulted with code SCRIPT_ERROR, its message naming the missing list endpoint and sync_runs gained a failed row
Scheduled firinga one-off trigger due at 05:30:00Z wrote a succeeded row at 05:30:01Z; the daily cron trigger 0 1 * * *, Asia/Shanghai, is enabled
Recordsdatabase db_53906c278792437a, script ops-hub/sync-backoffice-1795584503@1.0.0

Next steps

With the data in the database, build an analyst that writes a daily report; when the back office has to be changed, use actions after approval. The whole solution is the business operations hub.