Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: lottery-with-limits-of-wins-http-type #163

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions craft-functions/lottery-with-limits-of-wins/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ KARTE の接客サービスと Craft を組み合わせて、上限設定付き
## category

Craft Functions,Craft KVS,Craft Counter,KARTEイベント,CRAFT_ENDPOINT

## functionType

http
53 changes: 25 additions & 28 deletions craft-functions/lottery-with-limits-of-wins/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,50 +224,45 @@ async function determinePrize(rand, probabilities) {
* name or an error message.
*/
export default async function (data, { MODULES }) {
const { req, res } = data;
const { kvs, counter, initLogger, secret } = MODULES;
const logger = initLogger({ logLevel: LOG_LEVEL });
const secrets = await secret.get({ keys: [KARTE_APP_TOKEN_SECRET] });
const token = secrets[KARTE_APP_TOKEN_SECRET];

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

if (req.method === 'OPTIONS') {
res.status(204).end();
return;
}

try {
logger.debug('Starting the lucky draw process.');

if (PRIZES.length !== LIMITS.length) {
const errorMessage = 'PRIZES and LIMITS must have the same length.';
logger.error(errorMessage);
return { craft_status_code: 500, error: errorMessage };
res.status(500).json({ error: errorMessage });
return;
}

if (data.kind !== 'karte/track-hook') {
logger.error('Invalid request type. Expected "karte/track-hook".');
return { craft_status_code: 400, error: 'Invalid request type' };
}

const { jsonPayload } = data;
if (!jsonPayload?.data?.hook_data?.body) {
logger.error('Invalid payload: Missing required data');
return { craft_status_code: 400, error: 'Invalid payload' };
}

const {
body: { lotteryKey, userId },
} = jsonPayload.data.hook_data;
const { body } = req;
const { lotteryKey, userId } = body;
if (!lotteryKey || !userId) {
const missingKeyError = `Missing ${!lotteryKey ? 'lotteryKey' : 'userId'}`;
logger.warn(missingKeyError);
return {
craft_status_code: 400,
error: `${missingKeyError} is required.`,
};
res.status(400).json({ error: `${missingKeyError} is required.` });
return;
}

const hasParticipated = await hasParticipatedRecently({ lotteryKey, userId, kvs, logger });
if (hasParticipated) {
logger.debug(`User ${userId} has participated recently.`);
return {
craft_status_code: 400,
error: 'User has participated recently.',
};
res.status(400).json({ error: 'User has participated recently.' });
return;
}

const rand = Math.random();
Expand All @@ -289,7 +284,8 @@ export default async function (data, { MODULES }) {
});
await setParticipationTime({ lotteryKey, userId, kvs, logger });
logger.debug(`User ${userId} did not win any prize.`);
return { craft_status_code: 200, result: 'No prize won' };
res.status(200).json({ result: 'No prize won' });
return;
}

const { prize, index } = prizeResult;
Expand All @@ -310,15 +306,16 @@ export default async function (data, { MODULES }) {
logger,
});
logger.debug(`Prize ${prize} has reached its limit.`);
return { craft_status_code: 200, result: 'No prize won' };
res.status(200).json({ result: 'No prize won' });
return;
}

await sendKarteEvent({ userId, lotteryKey, prize, message: '', token, logger });
await setParticipationTime({ lotteryKey, userId, kvs, logger });
logger.debug(`User ${userId} won prize: ${prize}. ${LIMITS[index] - count} left.`);
return { craft_status_code: 200, result: prize };
res.status(200).json({ result: prize });
} catch (error) {
logger.error(`Error in the lucky draw process: ${error.toString()}`);
return { craft_status_code: 500, error: `Internal Server Error: ${error.message}` };
res.status(500).json({ error: `Internal Server Error: ${error.message}` });
}
}
}