Skip to content

Instantly share code, notes, and snippets.

@dps999
Created November 25, 2025 13:00
Show Gist options
  • Select an option

  • Save dps999/6b1d5f611bc71a9183c79d8c5c43088d to your computer and use it in GitHub Desktop.

Select an option

Save dps999/6b1d5f611bc71a9183c79d8c5c43088d to your computer and use it in GitHub Desktop.
SendGift.js
const { DataApi } = require("@unity-services/cloud-save-1.4");
const CUSTOM_ID = "gameGifts";
const GIFTS_KEY = "lifeGifts";
module.exports = async ({ params, context, logger }) => {
logger.info("Raw params object: " + JSON.stringify(params));
logger.info("Raw context: " + JSON.stringify(context));
const receiverId = params.receiverId || context.params?.receiverId;
const senderId = params.senderId || context.params?.senderId;
const senderName = params.senderName || context.params?.senderName;
const projectId = context.projectId;
logger.info(`Extracted - receiverId: ${receiverId}, senderId: ${senderId}, senderName: ${senderName}`);
const api = new DataApi(context);
try {
let gifts = [];
try {
const res = await api.getCustomItems(projectId, CUSTOM_ID, [GIFTS_KEY]);
const item = res.data?.results?.find(r => r.key === GIFTS_KEY);
if (item && item.value) {
const data = JSON.parse(item.value);
gifts = data.gifts || [];
}
} catch (e) {
logger.info("No existing gifts or failed to load, starting fresh: " + e.message);
}
const existingGift = gifts.find(
g => g.senderPlayerId === senderId && g.receiverPlayerId === receiverId
);
if (existingGift) {
return { error: "Gift already sent to this player" };
}
const newGift = {
id: generateId(),
senderPlayerId: senderId,
senderName: senderName,
receiverPlayerId: receiverId,
timestamp: Date.now()
};
logger.info("Created gift: " + JSON.stringify(newGift));
gifts.push(newGift);
await api.setCustomItem(projectId, CUSTOM_ID, {
key: GIFTS_KEY,
value: JSON.stringify({ gifts: gifts })
});
return { success: true, gift: newGift };
} catch (error) {
logger.error("Error sending gift: " + error.message);
throw error;
}
};
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).substr(2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment