forked from sajeetharan/devglobe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
192 lines (164 loc) · 7.18 KB
/
Copy pathserver.js
File metadata and controls
192 lines (164 loc) · 7.18 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
/**
* Local dev server — serves static files + /api/developers from Cosmos DB
*/
import express from 'express';
import { CosmosClient } from '@azure/cosmos';
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
dotenv.config();
const __dirname = dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = process.env.PORT || 3000;
const COSMOS_ENDPOINT = process.env.COSMOS_ENDPOINT;
const COSMOS_KEY = process.env.COSMOS_KEY;
const DATABASE = 'devglobe';
const CONTAINER = 'developers';
let cachedData = null;
let cacheTime = 0;
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
app.get('/api/developers', async (req, res) => {
res.setHeader('Content-Type', 'application/json');
if (!COSMOS_ENDPOINT || !COSMOS_KEY) {
return res.status(500).json({ error: 'Cosmos DB credentials not configured in .env' });
}
// Serve from memory cache if fresh
if (cachedData && Date.now() - cacheTime < CACHE_TTL) {
return res.json(cachedData);
}
try {
const client = new CosmosClient({ endpoint: COSMOS_ENDPOINT, key: COSMOS_KEY });
const container = client.database(DATABASE).container(CONTAINER);
const { resources } = await container.items
.query('SELECT * FROM c')
.fetchAll();
cachedData = resources;
cacheTime = Date.now();
console.log(`✓ Loaded ${resources.length} developers from Cosmos DB`);
res.json(resources);
} catch (err) {
console.error('Cosmos DB error:', err.message);
res.status(500).json({ error: 'Failed to fetch from Cosmos DB' });
}
});
// Search endpoint — supports text, vector, and hybrid search
app.get('/api/search', async (req, res) => {
res.setHeader('Content-Type', 'application/json');
const { q, mode = 'text', top = '10' } = req.query;
if (!q) return res.status(400).json({ error: 'Query parameter "q" is required' });
try {
const client = new CosmosClient({ endpoint: COSMOS_ENDPOINT, key: COSMOS_KEY });
const container = client.database(DATABASE).container(CONTAINER);
const limit = Math.min(parseInt(top) || 10, 50);
let results;
if (mode === 'vector' || mode === 'hybrid') {
const OPENAI_ENDPOINT = process.env.AZURE_OPENAI_ENDPOINT;
const OPENAI_KEY = process.env.AZURE_OPENAI_KEY;
const DEPLOYMENT = process.env.EMBEDDING_DEPLOYMENT || 'text-embedding-3-small';
if (!OPENAI_ENDPOINT || !OPENAI_KEY) {
return res.status(500).json({ error: 'OpenAI not configured for vector search' });
}
// Generate embedding for the query
const embRes = await fetch(
`${OPENAI_ENDPOINT}/openai/deployments/${DEPLOYMENT}/embeddings?api-version=2024-02-01`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', 'api-key': OPENAI_KEY },
body: JSON.stringify({ input: [q] })
}
);
const embData = await embRes.json();
const embedding = embData.data[0].embedding;
// Vector search
const { resources: vectorResults } = await container.items.query({
query: `SELECT TOP ${limit}
c.id, c.login, c.name, c.avatarUrl, c.location, c.lat, c.lng,
c.topLanguage, c.score, c.totalStars, c.followers, c.soReputation,
c.bio, c.totalCommits, c.scoreDimensions,
VectorDistance(c.embedding, @emb) AS similarity
FROM c ORDER BY VectorDistance(c.embedding, @emb)`,
parameters: [{ name: '@emb', value: embedding }]
}).fetchAll();
if (mode === 'vector') {
results = vectorResults;
} else {
// Hybrid: also run text search and merge with RRF
const searchTerm = q.toLowerCase();
const { resources: textResults } = await container.items.query({
query: `SELECT TOP ${limit}
c.id, c.login, c.name, c.avatarUrl, c.location, c.lat, c.lng,
c.topLanguage, c.score, c.totalStars, c.followers, c.soReputation,
c.bio, c.totalCommits, c.scoreDimensions
FROM c
WHERE CONTAINS(LOWER(c.login), @q)
OR CONTAINS(LOWER(c.name), @q)
OR CONTAINS(LOWER(c.location), @q)
OR CONTAINS(LOWER(c.bio), @q)
OR CONTAINS(LOWER(c.topLanguage), @q)
ORDER BY c.score DESC`,
parameters: [{ name: '@q', value: searchTerm }]
}).fetchAll();
// Client-side RRF
const rrf = new Map();
const k = 60;
vectorResults.forEach((r, i) => rrf.set(r.login, (rrf.get(r.login) || 0) + 1 / (k + i + 1)));
textResults.forEach((r, i) => rrf.set(r.login, (rrf.get(r.login) || 0) + 1 / (k + i + 1)));
const allMap = new Map();
[...vectorResults, ...textResults].forEach(r => allMap.set(r.login, r));
results = [...rrf.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([login]) => allMap.get(login));
}
} else {
// Text search
const searchTerm = q.toLowerCase();
const { resources } = await container.items.query({
query: `SELECT TOP ${limit}
c.id, c.login, c.name, c.avatarUrl, c.location, c.lat, c.lng,
c.topLanguage, c.score, c.totalStars, c.followers, c.soReputation,
c.bio, c.totalCommits, c.scoreDimensions
FROM c
WHERE CONTAINS(LOWER(c.login), @q)
OR CONTAINS(LOWER(c.name), @q)
OR CONTAINS(LOWER(c.location), @q)
OR CONTAINS(LOWER(c.bio), @q)
OR CONTAINS(LOWER(c.topLanguage), @q)
ORDER BY c.score DESC`,
parameters: [{ name: '@q', value: searchTerm }]
}).fetchAll();
results = resources;
}
console.log(`🔍 Search "${q}" (${mode}) → ${results.length} results`);
res.json({ query: q, mode, count: results.length, results });
} catch (err) {
console.error('Search error:', err.message);
res.status(500).json({ error: 'Search failed' });
}
});
// Single developer detail endpoint
app.get('/api/developer', async (req, res) => {
res.setHeader('Content-Type', 'application/json');
const { id } = req.query;
if (!id) return res.status(400).json({ error: 'Query parameter "id" is required' });
try {
const client = new CosmosClient({ endpoint: COSMOS_ENDPOINT, key: COSMOS_KEY });
const container = client.database(DATABASE).container(CONTAINER);
const { resources } = await container.items.query({
query: 'SELECT c.id, c.login, c.name, c.avatarUrl, c.bio, c.location, c.lat, c.lng, c.followers, c.totalStars, c.totalForks, c.totalCommits, c.topLanguage, c.languages, c.publicRepos, c.topRepos, c.soReputation, c.soAnswers, c.soAcceptRate, c.soBadges, c.soUserId FROM c WHERE c.id = @id',
parameters: [{ name: '@id', value: id }]
}).fetchAll();
if (resources.length === 0) return res.status(404).json({ error: 'Developer not found' });
res.json(resources[0]);
} catch (err) {
console.error('Detail error:', err.message);
res.status(500).json({ error: 'Failed to fetch developer' });
}
});
// Serve static files
app.use(express.static(__dirname));
// SPA fallback
app.use((req, res) => {
res.sendFile(join(__dirname, 'index.html'));
});
app.listen(PORT, () => {
console.log(`\n DevGlobe server running at http://localhost:${PORT}`);
console.log(` Data source: Cosmos DB (${COSMOS_ENDPOINT})\n`);
});