Skip to content
This repository was archived by the owner on Oct 28, 2024. It is now read-only.

Commit 3d7f2be

Browse files
committed
add logging
1 parent 38c0d1f commit 3d7f2be

File tree

4 files changed

+73
-53
lines changed

4 files changed

+73
-53
lines changed

index.ts

Lines changed: 64 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,95 @@
1-
import { Router, IRequest } from 'itty-router';
1+
import { Router, IRequest } from "itty-router";
22

33
// Constants
4-
const API_ENDPOINT = 'https://api.mailchannels.net/tx/v1/send';
5-
const CONTENT_TYPE_JSON = 'application/json';
4+
const API_ENDPOINT = "https://api.mailchannels.net/tx/v1/send";
5+
const CONTENT_TYPE_JSON = "application/json";
66

77
// Helper function to create a response
88
const createResponse = (body: any, status: number) =>
9-
new Response(JSON.stringify(body), {
10-
headers: { 'content-type': CONTENT_TYPE_JSON },
11-
status,
12-
});
9+
new Response(JSON.stringify(body), {
10+
headers: { "content-type": CONTENT_TYPE_JSON },
11+
status,
12+
});
1313

1414
// Curry function for handling errors
1515
const handleError = (status: number) => (message: string, request: IRequest) =>
16-
createResponse({ error: message }, status);
16+
createResponse({ error: message }, status);
1717

1818
// Middleware for authentication
1919
const authMiddleware = (token: string | null) => (request: IRequest) => {
20-
const requestToken = request.headers.get('Authorization');
20+
const requestToken = request.headers.get("Authorization");
2121

22-
const unauthorizedError = handleError(401)('Unauthorized', request);
23-
const missingTokenError = handleError(401)('You must set the TOKEN environment variable.', request);
22+
const unauthorizedError = handleError(401)("Unauthorized", request);
23+
const missingTokenError = handleError(401)(
24+
"You must set the TOKEN environment variable.",
25+
request
26+
);
2427

25-
return token
26-
? requestToken === token
27-
? null
28-
: unauthorizedError
29-
: missingTokenError;
28+
return token
29+
? requestToken === token
30+
? null
31+
: unauthorizedError
32+
: missingTokenError;
3033
};
3134

3235
// Service function to send email
3336
const sendEmail = async (email: any) => {
34-
const resp = await fetch(API_ENDPOINT, {
35-
method: 'POST',
36-
headers: {
37-
'content-type': CONTENT_TYPE_JSON,
38-
},
39-
body: JSON.stringify(email),
40-
});
41-
42-
if (!resp.ok) {
43-
const errorMessage = `Error sending email: ${resp.status} ${resp.statusText}`;
44-
throw new Error(`${errorMessage}\n${await resp.text()}`);
45-
}
37+
const resp = await fetch(API_ENDPOINT, {
38+
method: "POST",
39+
headers: {
40+
"content-type": CONTENT_TYPE_JSON,
41+
},
42+
body: JSON.stringify(email),
43+
});
44+
45+
if (!resp.ok) {
46+
const errorMessage = `Error sending email: ${resp.status} ${resp.statusText}`;
47+
throw new Error(`${errorMessage}\n${await resp.text()}`);
48+
}
49+
};
50+
51+
// Log batch of emails
52+
const logBatch = async (emails: any[], env: Env) => {
53+
if (emails.length > 0) {
54+
await Promise.all(
55+
emails.map((email) => env.log.put(`${Date.now()}`, JSON.stringify(email)))
56+
);
57+
}
4658
};
4759

4860
// Route handler for sending email
4961
const sendEmailHandler = async (request: IRequest, env: Env) => {
50-
try {
51-
const authError = authMiddleware(env.TOKEN)(request);
52-
if (authError) return authError;
53-
54-
const email = await request.json();
55-
await sendEmail(email);
56-
57-
return createResponse({
58-
status: 'SUCCESS',
59-
statusCode: 1000,
60-
message: 'NA',
61-
}, 200);
62-
} catch (error) {
63-
console.error(`Error processing request: ${error}`);
64-
return handleError(500)('Internal Server Error', request);
65-
}
62+
try {
63+
const authError = authMiddleware(env.TOKEN)(request);
64+
if (authError) return authError;
65+
66+
const email = await request.json();
67+
await sendEmail(email);
68+
69+
logBatch([email], env);
70+
71+
return createResponse(
72+
{
73+
status: "SUCCESS",
74+
statusCode: 1000,
75+
message: "NA",
76+
},
77+
200
78+
);
79+
} catch (error) {
80+
console.error(`Error processing request: ${error}`);
81+
return handleError(500)("Internal Server Error", request);
82+
}
6683
};
6784

6885
// Create router
6986
const router = Router();
7087

7188
// Define routes
72-
router.post('/api/email', sendEmailHandler);
73-
router.all('*', (request: IRequest) => handleError(404)('Not Found', request));
89+
router.post("/api/email", sendEmailHandler);
90+
router.all("*", (request: IRequest) => handleError(404)("Not Found", request));
7491

7592
// Export the router handler
7693
export default {
77-
fetch: router.handle,
94+
fetch: router.handle,
7895
};

package.json

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
{
2-
"name": "email",
2+
"name": "email-proxy",
33
"version": "0.0.0",
44
"private": true,
55
"scripts": {
66
"deploy": "wrangler publish",
7-
"start": "wrangler dev"
7+
"dev": "wrangler dev"
88
},
99
"devDependencies": {
1010
"@cloudflare/workers-types": "^4.20230419.0",
@@ -13,7 +13,6 @@
1313
"typescript": "^5.0.4"
1414
},
1515
"dependencies": {
16-
"wrangler": "^3.1.1",
17-
"zod": "^3.22.4"
16+
"wrangler": "^3.1.1"
1817
}
1918
}

worker-configuration.d.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
interface Env {
2-
TOKEN: string;
2+
TOKEN: string;
3+
log: KVNamespace;
34
}

wrangler.toml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
name = "email"
1+
name = "email-proxy"
22
main = "index.ts"
33
compatibility_date = "2023-05-18"
44

5+
kv_namespaces = [
6+
{ binding = "log", id = "cfa4e6ed8c054bf5bcb3cb4d0ab107fb", preview_id = "cec98816e55748fd958c0fec7db67131" },
7+
]

0 commit comments

Comments
 (0)