-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
234 lines (203 loc) · 5.87 KB
/
app.js
File metadata and controls
234 lines (203 loc) · 5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Import required modules
const http = require('http');
const express = require('express');
const { Client } = require('@notionhq/client');
const dotenv = require('dotenv');
const path = require('path');
// Load environment variables
dotenv.config();
// Create Express app
const app = express();
// Middleware
app.use(express.json());
app.use(express.static('public'));
// Initialize Notion client
const notion = new Client({
auth: process.env.NOTION_API_KEY,
});
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Endpoint to get database structure
app.get('/api/database', async (req, res) => {
try {
const database = await notion.databases.retrieve({
database_id: process.env.NOTION_DATABASE_ID,
});
res.json(database);
} catch (error) {
console.error('Error retrieving database:', error.stack); // Log full error stack
res.status(500).json({ error: 'Failed to retrieve database', message: error.message }); // Include error message
}
});
// Endpoint to update a page with an address
app.post('/api/update-address', async (req, res) => {
// Extract locality, state, and country from the request body
const { pageId, propertyName, address, placeId, lat, lng, url, website, name, locality, state, country } = req.body;
// Ensure these values are defined or default to empty strings
const localityValue = locality || '';
const stateValue = state || '';
const countryValue = country || '';
try {
// Retrieve the current page details
const page = await notion.pages.retrieve({ page_id: pageId });
const currentPageName = page.properties.title?.title?.[0]?.text?.content || '';
// Check if the name is different from the current page name
if (name && name !== currentPageName) {
// Update the page name
await notion.pages.update({
page_id: pageId,
properties: {
title: {
title: [
{
text: {
content: name
}
}
]
}
}
});
}
// Build properties object dynamically
const properties = {
[propertyName]: {
rich_text: [
{
text: {
content: address
}
}
]
},
"Place ID": {
rich_text: [
{
text: {
content: placeId
}
}
]
},
"URL": {
url: url
},
"Website": {
url: website
},
"Latitude": {
rich_text: [
{
text: {
content: lat.toString()
}
}
]
},
"Longitude": {
rich_text: [
{
text: {
content: lng.toString()
}
}
]
},
"Locality": {
select: {
name: localityValue
}
},
"State": {
select: {
name: stateValue
}
},
"Country": {
select: {
name: countryValue
}
}
};
// Update the page with the address data
const response = await notion.pages.update({
page_id: pageId,
properties
});
res.json({ success: true, response });
} catch (error) {
console.error('Error updating page:', error.stack); // Log full error stack
res.status(500).json({ error: 'Failed to update page', message: error.message }); // Include error message
}
});
// Get pages from database
app.get('/api/pages', async (req, res) => {
try {
const response = await notion.databases.query({
database_id: process.env.NOTION_DATABASE_ID,
page_size: 100,
});
res.json(response);
} catch (error) {
console.error('Error querying database:', error.stack); // Log full error stack
res.status(500).json({ error: 'Failed to query database', message: error.message }); // Include error message
}
});
// Endpoint to expose Google API Key
app.get('/api/google-api-key', (req, res) => {
try {
res.json({ apiKey: process.env.GOOGLE_API_KEY });
} catch (error) {
console.error('Error exposing Google API Key:', error.stack); // Log full error stack
res.status(500).json({ error: 'Failed to expose Google API Key', message: error.message }); // Include error message
}
});
// Webhook endpoint to handle Notion events
app.post('/api/webhook', async (req, res) => {
const event = req.body;
if (event.challenge) return res.status(200).send(event.challenge);
if (event.type === 'page.created') {
const pageId = event.entity.id;
try {
const page = await notion.pages.retrieve({ page_id: pageId });
const inputAddress = page.properties["Address"]?.rich_text?.[0]?.text?.content;
console.log('Input address:', inputAddress); // Log the input address
if (!inputAddress) return res.status(200).send('No address provided.');
// Call your autocomplete API (already implemented)
const autocompleteRes = await fetch('https://notion-api-address-autocomplete.blank-space.online/api/autocomplete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: inputAddress })
});
const data = await autocompleteRes.json();
console.log('Autocomplete data:', data); // Log the autocomplete data
console.log("Sending update to Notion:", pageId, data);
// Update Notion page using your API
await fetch('https://notion-api-address-autocomplete.blank-space.online/api/update-address', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pageId,
propertyName: "Address", // still the same
...data // includes Website, URL, Latitude, Longitude, Locality, State, Country
})
});
console.log("Update address request body:", req.body); // Log the request body
res.status(200).send('Autocomplete completed and fields updated');
} catch (error) {
console.error('Error processing webhook:', error);
res.status(500).send('Webhook processing failed');
}
} else {
res.status(200).send('Unhandled event type');
}
});
// Create HTTP server with Express
const server = http.createServer(app);
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});