connect-the-dots / cloud-js / BatchInrementNumCompletion.js
BatchInrementNumCompletion.js
Raw
const { DataApi } = require("@unity-services/cloud-save-1.4");

module.exports = async ({ params, context }) => {
  const { projectId } = context;
  const deltas = params.deltas || {};
  const keys = Object.keys(deltas);
  if (!keys.length) return { newTotals: {} };

  const cloudSave = new DataApi(context);
  const COLL = "level-stats";
  const KEY = "level-completion";

  const read = await cloudSave.getPrivateCustomItems(projectId, COLL, [KEY]);
  const blob = read.data.results[0] ?? { value: {}, metadata: {} };
  const stats = blob.value;

  const newTotals = {};
  for (const k of keys) {
    const prev = stats[k]?.NumCompletions || 0;
    const updated = prev + Number(deltas[k] || 0);
    stats[k] = { NumCompletions: updated };
    newTotals[k] = updated;
  }

  await cloudSave.setPrivateCustomItemBatch(projectId, COLL, {
    data: [{
      key: KEY,
      value: stats,
      writeLock: blob.metadata?.etag
    }]
  });

  return { NewTotals: newTotals };
};