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: events-from-webhook-http-type #157

Merged
merged 2 commits into from
Oct 9, 2024
Merged
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
6 changes: 5 additions & 1 deletion craft-functions/events-from-webhook/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ https://solution.karte.io/blog/2024/01/webhook-event

## category

外部連携,Craft Functions,CRAFT_ENDPOINT
外部連携,Craft Functions,CRAFT_ENDPOINT

## functionType

http
22 changes: 18 additions & 4 deletions craft-functions/events-from-webhook/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import api from 'api';

const karteApiClient = api('@dev-karte/v1.0#1jvnhd6llgekil84');
const LOG_LEVEL = '<% LOG_LEVEL %>';
const KARTE_APP_TOKEN_SECRET = '<% KARTE_APP_TOKEN_SECRET %>';
Expand All @@ -13,7 +14,9 @@ export default async function (data, { MODULES }) {
const secrets = await secret.get({ keys: [KARTE_APP_TOKEN_SECRET] });
const token = secrets[KARTE_APP_TOKEN_SECRET];
karteApiClient.auth(token);
const payload = data.jsonPayload.data.hook_data.body.payload;

const { req, res } = data;
const payload = req.body.payload;
const userId = payload[USER_ID_FIELD];

const values = {};
Expand All @@ -22,16 +25,27 @@ export default async function (data, { MODULES }) {
values[field] = payload[field];
});

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 {
await karteApiClient.postV2betaTrackEventWriteandexecaction({
keys: { visitor_id: VISTOR_ID_PREFIX + '-' + userId },
keys: { visitor_id: `${VISTOR_ID_PREFIX}-${userId}` },
event: {
event_name: EVENT_NAME,
values,
},
});
logger.log(EVENT_NAME + 'Event sent successfully.');
logger.log(`Event sent successfully. event_name: ${EVENT_NAME}`);
res.status(200).json({ message: 'Success' });
} catch (e) {
logger.error(e);
res.status(500).json({ error: e.message });
}
}
}