Skip to content
Agentpost robot in sunglasses on a red circleAgentpost

Book time slots

Use this guide to book time from your server: list the free hours, hold and commit a booking, move it, and cancel it. To give principals a page that books, follow Build a booking page after this guide. A line that a hold commits over a span becomes a booking. Schedules explains buckets and weekly hours, and Claims explains bookings.

Check your business rules on your server before each call: which court to book, how far ahead and how long, and whether a booking may move or be canceled. In the code tabs, run the HTTP tab or the SDK tab with the shared blocks. The ResourceShark SDK package is @agentpost-tools/resourceshark-sdk.

Before you start

This page's code continues the script of the pages above: run its blocks after theirs, in the same file. To run them as a script of their own, first copy each helper from the page that defines it, and set each other value, such as a key or an ID, to one you already have.

1. Create two courts with weekly hours

Use api and the dev secret key key for a project that adopted ResourceShark. Create two courts. Each takes one booking per hour, in hourly buckets in Asia/Jakarta. Save the same schedule on each: open from 07:00 to 22:00 every day. A new court has no bookings, so the save leaves no bucket over capacity. Run the blocks in order on your server. Save a schedule has the request’s fields and says what overCapacity lists.

const clubRun = crypto.randomUUID();
const clubWrite = (path: string, attempt: string, body: unknown) =>
  api('POST', `/v1/resources${path}`, key, body, {
    'Idempotency-Key': `${clubRun}:${attempt}`,
  });

const courtFields = {
  unit: { code: 'court', singular: 'court', plural: 'courts', precision: 0 },
  settings: {
    time: 'buckets',
    bucket: { size: 'step', stepMinutes: 60, timeZone: 'Asia/Jakarta' },
    identity: 'count',
    supplyExpiry: 'none',
  },
  scope: { places: false, holders: false },
  tracking: 'none',
  shortage: 'deny',
  capacity: 1,
};
const clubHours = {
  timeZone: 'Asia/Jakarta',
  patterns: [
    {
      weekly: [0, 1, 2, 3, 4, 5, 6].map((day) => ({
        day,
        start: '07:00',
        end: '22:00',
      })),
    },
  ],
};

async function createCourt(number: number) {
  const { resource: court } = await api(
    'POST',
    '/v1/resources/resources',
    key,
    {
      ...courtFields,
      key: `court-${number}-${clubRun}`,
      name: `Court ${number}`,
    },
  );
  const saved = await api(
    'PUT',
    `/v1/resources/resources/${court.id}/schedule`,
    key,
    clubHours,
  );
  return { court, saved };
}
const { court: courtOne } = await createCourt(1);
const { court: courtTwo, saved: courtTwoHours } = await createCourt(2);
const clubCourts = [courtOne, courtTwo];
console.log(
  courtTwoHours.schedule.version,
  courtTwoHours.overCapacity.buckets.length,
); // 1 0

2. List a day’s free hours

Read tomorrow’s slots on Court 1 from 07:00 to 22:00 in Jakarta. Jakarta keeps UTC+7 all year, so tomorrow’s date there is the UTC date 31 hours from now. Each slot gives its start on the court’s clock in local, and what is free in available. This app also shows each hour in the member’s own time zone, Asia/Singapore. With the SDK, slotIn reads a slot in any time zone you name.

Which court to book is your app’s rule. This club takes the first court, in the order it created them, that has the hour free. Reading slots reserves nothing. List slots has every query parameter and what each slot gives.

const clubDay = new Date(Date.now() + 31 * 3_600_000)
  .toISOString()
  .slice(0, 10);
const clubAt = (time: string) =>
  new Date(`${clubDay}T${time}:00+07:00`).toISOString();
const tenHour = { start: clubAt('10:00'), end: clubAt('11:00') };
const elevenHour = { start: clubAt('11:00'), end: clubAt('12:00') };
const memberZone = 'Asia/Singapore';
async function readCourtSlots(courtId: string, from: string, to: string) {
  const query = new URLSearchParams({ resourceId: courtId, from, to });
  const { slots } = await api('GET', `/v1/resources/slots?${query}`, key);
  return slots;
}
const memberClock = new Intl.DateTimeFormat('en-GB', {
  timeZone: memberZone,
  hour: '2-digit',
  minute: '2-digit',
  hourCycle: 'h23',
});
const memberTime = (slot: { start: string }) =>
  memberClock.format(new Date(slot.start));
import {
  createClient as createClubClient,
  type Slot,
} from '@agentpost-tools/resourceshark-sdk';
import { slotIn } from '@agentpost-tools/resourceshark-sdk/helpers';

const clubClient = createClubClient({ token: key });
async function readCourtSlots(courtId: string, from: string, to: string) {
  const { slots } = await clubClient.slots.list({
    resourceId: courtId,
    from,
    to,
  });
  return slots;
}
const memberTime = (slot: Slot) => slotIn(slot, memberZone).time;

Both tabs leave readCourtSlots and memberTime ready to use.

const courtOneDay = await readCourtSlots(
  courtOne.id,
  clubAt('07:00'),
  clubAt('22:00'),
);
const [openingHour] = courtOneDay;
console.log(
  courtOneDay.length,
  openingHour.local.time,
  memberTime(openingHour),
  openingHour.available,
); // 15 07:00 08:00 1

async function firstFreeCourt(hour: { start: string; end: string }) {
  for (const court of clubCourts) {
    const [slot] = await readCourtSlots(court.id, hour.start, hour.end);
    if (slot && slot.available > 0) return court;
  }
  return undefined;
}

3. Hold and commit a booking

Rina asks for 10:00. Hold the first free court for 15 minutes while Rina pays. Every hold sends a ttl, which your app chooses. The line names the court and the span it takes, and holderRef says who the booking is for. Commit the hold with the order as evidence. The committed line is a booking, a claim of kind booking.

async function bookCourt(
  member: string,
  courtId: string,
  hour: { start: string; end: string },
) {
  const { hold } = await clubWrite('/holds', `hold-${member}`, {
    lines: [{ resourceId: courtId, quantity: 1, span: hour }],
    ttl: '15m',
    holderRef: `member:${member}`,
    sourceKey: `court-hold:${clubRun}:${member}`,
  });
  const { hold: booking } = await clubWrite(
    `/holds/${hold.id}/commit`,
    `commit-${member}`,
    {
      evidence: { kind: 'order', ref: `order-${member}-${clubRun}` },
      sourceKey: `court-order:${clubRun}:${member}`,
    },
  );
  return booking;
}

const rinaCourt = await firstFreeCourt(tenHour);
if (!rinaCourt) throw new Error('No court is free at 10:00');
const rinaBooking = await bookCourt('rina', rinaCourt.id, tenHour);
const { claim: rinaClaim } = await api(
  'GET',
  `/v1/resources/claims/${rinaBooking.lines[0].claimId}`,
  key,
);
console.log(rinaCourt.name, rinaBooking.status, rinaClaim.kind); // Court 1 committed booking

4. See a second booking of the same hour refused

Budi asks for Court 1 at 10:00 too. ResourceShark refuses the hold with insufficient_supply and takes nothing. The refusal’s details.lines says the line asked for one court and has none free. clubRefusal reads it from the error api throws.

Your app then applies its court rule again and books Court 2. The new attempt keeps the checkout’s sourceKey and sends a new Idempotency-Key.

async function clubRefusal(path: string, attempt: string, body: unknown) {
  try {
    await api('POST', `/v1/resources${path}`, key, body, {
      'Idempotency-Key': `${clubRun}:${attempt}`,
    });
  } catch (thrown) {
    const { error } = thrown as { error?: any };
    if (!error) throw thrown;
    return error;
  }
  throw new Error(`Expected ${path} to be refused`);
}

const budiRefusal = await clubRefusal('/holds', 'hold-budi-court-1', {
  lines: [{ resourceId: courtOne.id, quantity: 1, span: tenHour }],
  ttl: '15m',
  holderRef: 'member:budi',
  sourceKey: `court-hold:${clubRun}:budi`,
});
const [budiShort] = budiRefusal.details.lines;
console.log(budiRefusal.code, budiShort.quantity, budiShort.available); // insufficient_supply 1 0

const budiCourt = await firstFreeCourt(tenHour);
if (!budiCourt) throw new Error('No court is free at 10:00');
const budiBooking = await bookCourt('budi', budiCourt.id, tenHour);
console.log(budiCourt.name, budiBooking.status); // Court 2 committed

5. Move a booking to another hour and court

Rina asks to play at 11:00 on Court 2 instead. Send POST /reschedule with one line: the booked line’s claimId, the new resourceId, and the new span. ResourceShark gives back Court 1 at 10:00 and takes Court 2 at 11:00 in one write, or changes nothing. The line keeps its claim ID and stays committed.

A line that names a resource names its scope there in full. A court has no place or holder, so this line sends no scope. The new resource must count in the same unit, with the same code and precision. Send the required sourceKey. Repeating the same move request with that key answers with the original moves and the current holds, with duplicate: true. Reschedule a hold has the request’s fields and its errors.

const rinaMove = {
  lines: [
    {
      claimId: rinaBooking.lines[0].claimId,
      resourceId: courtTwo.id,
      span: elevenHour,
    },
  ],
  evidence: { kind: 'change-request', ref: `rina-move-${clubRun}` },
  sourceKey: `court-move:${clubRun}:rina-1`,
};
const rinaMoved = await clubWrite('/reschedule', 'move-rina-1', rinaMove);
const rinaMoved = await clubClient.holds.reschedule(rinaMove, {
  idempotencyKey: `${clubRun}:move-rina-1`,
});

Both tabs leave rinaMoved ready to use. Its lines give each moved line’s position before and after, and its holds give each hold as it now is.

const [rinaLine] = rinaMoved.lines;
console.log(
  rinaLine.before.resourceId === courtOne.id,
  rinaLine.after.resourceId === courtTwo.id,
  rinaLine.after.span.start === elevenHour.start,
  rinaMoved.holds[0].status,
); // true true true committed

6. See a move to a full hour refused

Rina then asks for Court 2 at 10:00, which Budi booked. The line names only a new span, so it keeps its court. ResourceShark refuses the move with insufficient_supply and what the line has available, and nothing moves. Rina’s booking stays at 11:00.

const fullMove = await clubRefusal('/reschedule', 'move-rina-2', {
  lines: [{ claimId: rinaLine.claimId, span: tenHour }],
  sourceKey: `court-move:${clubRun}:rina-2`,
});
const { hold: rinaUnmoved } = await api(
  'GET',
  `/v1/resources/holds/${rinaBooking.id}`,
  key,
);
console.log(
  fullMove.code,
  fullMove.details.lines[0].available,
  rinaUnmoved.lines[0].span.start === elevenHour.start,
); // insufficient_supply 0 true

7. Swap two bookings on two full courts

Ana books Court 1 at 11:00, so both courts are full at that hour. Rina and Ana agree to trade courts. Send both lines in one request. Every line gives back its court before any line takes one, so the swap fits. Sent one at a time, each move would be refused.

const anaBooking = await bookCourt('ana', courtOne.id, elevenHour);
const { holds: swappedHolds } = await clubWrite(
  '/reschedule',
  'swap-rina-ana',
  {
    lines: [
      { claimId: rinaLine.claimId, resourceId: courtOne.id },
      { claimId: anaBooking.lines[0].claimId, resourceId: courtTwo.id },
    ],
    sourceKey: `court-move:${clubRun}:swap-rina-ana`,
  },
);
console.log(
  swappedHolds[0].lines[0].resourceId === courtOne.id,
  swappedHolds[1].lines[0].resourceId === courtTwo.id,
); // true true

8. Cancel a booking

Budi cancels. Cancel Budi’s committed hold with POST /holds/:id/cancel. With lines left out, the cancel gives back every committed line. Court 2 at 10:00 is free again, and the hold reads cancelled. Cancel a committed hold has the request’s fields and its errors.

const { hold: budiCancelled, movements: budiReturned } = await clubWrite(
  `/holds/${budiBooking.id}/cancel`,
  'cancel-budi',
  {
    evidence: { kind: 'cancellation', ref: `budi-cancel-${clubRun}` },
    sourceKey: `court-cancel:${clubRun}:budi`,
  },
);
console.log(budiCancelled.status, budiReturned[0].quantity); // cancelled 1

9. Book rooms by number

Skip this step when your units are interchangeable, like these courts. A hotel books a room by its number. Create a resource with settings.identity: 'instance' in nightly buckets, and add each room as an instance. A resource that tells its units apart has no capacity and counts whole units, at precision 0. If it counts time in buckets, set both scope.places and scope.holders to false. Each room’s night holds that room or nothing.

List the rooms free for every night of a stay with GET /resources/:id/free-instances, sending from and to. Pick a room from that list and name it in each line’s scope.instanceId, with a quantity of 1. A stay that names a room already taken for any of its nights is refused with assignment_infeasible. To move a stay to another room, send the same resourceId with the new room in scope.instanceId. A held line moves the same way as a committed one, and its hold keeps its expiresAt. List free instances has every query parameter and how the list pages.

const { resource: guestRooms } = await api(
  'POST',
  '/v1/resources/resources',
  key,
  {
    key: `guest-room-${clubRun}`,
    name: 'Guest room',
    unit: { code: 'room', singular: 'room', plural: 'rooms', precision: 0 },
    settings: {
      time: 'buckets',
      bucket: { size: 'day', timeZone: 'Asia/Jakarta' },
      identity: 'instance',
      supplyExpiry: 'none',
    },
    scope: { places: false, holders: false },
    tracking: 'none',
    shortage: 'deny',
  },
);
const roomPath = `/v1/resources/resources/${guestRooms.id}`;
const { instance: room204 } = await api('POST', `${roomPath}/instances`, key, {
  code: '204',
  status: 'active',
});
const { instance: room205 } = await api('POST', `${roomPath}/instances`, key, {
  code: '205',
  status: 'active',
});

const firstNight = Date.parse(`${clubDay}T00:00:00+07:00`);
const stayNights = {
  start: new Date(firstNight).toISOString(),
  end: new Date(firstNight + 2 * 86_400_000).toISOString(),
};
const stayQuery = new URLSearchParams({
  from: stayNights.start,
  to: stayNights.end,
});
async function freeRooms() {
  const { instances } = await api(
    'GET',
    `${roomPath}/free-instances?${stayQuery}`,
    key,
  );
  return instances;
}
const roomLine = (instanceId: string) => ({
  resourceId: guestRooms.id,
  scope: { instanceId },
  quantity: 1,
  span: stayNights,
});

const roomsBefore = await freeRooms();
const { hold: anaStay } = await clubWrite('/holds', 'stay-ana', {
  lines: [roomLine(room204.id)],
  ttl: '15m',
  holderRef: 'guest:ana',
  sourceKey: `room-hold:${clubRun}:ana`,
});
const roomTaken = await clubRefusal('/holds', 'stay-budi', {
  lines: [roomLine(room204.id)],
  ttl: '15m',
  holderRef: 'guest:budi',
  sourceKey: `room-hold:${clubRun}:budi`,
});
const anaRoomMove = await clubWrite('/reschedule', 'move-stay-ana', {
  lines: [
    {
      claimId: anaStay.lines[0].claimId,
      resourceId: guestRooms.id,
      scope: { instanceId: room205.id },
    },
  ],
  sourceKey: `room-move:${clubRun}:ana`,
});
const roomsAfter = await freeRooms();
console.log(
  roomsBefore.length,
  roomTaken.code,
  anaRoomMove.lines[0].after.scope.instanceId === room205.id,
  roomsAfter.map(({ code }: { code: string }) => code).join(' '),
); // 2 assignment_infeasible true 204

Check it worked

Read both courts’ slots at 10:00 and 11:00. Court 1 is free at 10:00, and Rina has it at 11:00. Court 2 is free at 10:00 after Budi’s cancel, and Ana has it at 11:00.

const courtsNow = await Promise.all(
  clubCourts.map(({ id }) => readCourtSlots(id, tenHour.start, elevenHour.end)),
);
console.log(...courtsNow.flat().map(({ available }) => available)); // 1 0 1 0

Next, Build a booking page lists these hours on a page and holds one through your server.