-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
135 lines (117 loc) · 4.82 KB
/
Copy pathserver.js
File metadata and controls
135 lines (117 loc) · 4.82 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
import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import { createClient } from '@supabase/supabase-js';
import fetch from 'node-fetch';
// ─── Express App ────────────────────────────────────────────────────────────
const app = express();
app.use(cors()); // Allow all origins — Framer, browsers, Postman
app.use(express.json());
// ─── Supabase Client ─────────────────────────────────────────────────────────
const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_KEY
);
// ─── Gemini Embedding Helper ──────────────────────────────────────────────────
/**
* Calls the Gemini embedding API and returns a 768-dimensional vector.
* @param {string} text - The text to embed.
* @returns {Promise<number[]>} - The embedding vector.
*/
async function getEmbedding(text) {
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent?key=${process.env.GEMINI_API_KEY}`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
content: {
parts: [{ text }],
},
outputDimensionality: 768,
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Gemini API error (${response.status}): ${error}`);
}
const data = await response.json();
// Shape: { embedding: { values: [number, ...] } }
return data.embedding.values;
}
// ─── Routes ──────────────────────────────────────────────────────────────────
// Health check
app.get('/', (req, res) => {
res.json({ status: 'ok', message: 'pd_semantic_search server is running' });
});
/**
* POST /embed
* Body: { "text": "some string to embed" }
* Returns: { "embedding": [768 numbers] }
*/
app.post('/embed', async (req, res) => {
const { text } = req.body;
if (!text || typeof text !== 'string') {
return res.status(400).json({ error: '`text` field (string) is required.' });
}
try {
const embedding = await getEmbedding(text);
return res.json({ embedding });
} catch (err) {
console.error('Error generating embedding:', err.message);
return res.status(500).json({ error: err.message });
}
});
/**
* POST /search
*
* Body:
* {
* "query": "3 bedroom apartment in Abuja near schools under 5 million", // required
* "bedrooms": 3, // optional filter
* "max_price": 5000000, // optional filter
* "city": "Abuja", // optional filter
* "listing_type": "rent", // optional filter: "rent" | "sale"
* "limit": 5 // optional, default 5
* }
*
* Returns: { results: [ { id, title, city, area, bedrooms, bathrooms, price, listing_type, description, similarity } ] }
*/
app.post('/search', async (req, res) => {
const {
query,
bedrooms,
max_price,
city,
listing_type,
limit = 5,
} = req.body;
if (!query || typeof query !== 'string') {
return res.status(400).json({ error: '`query` field (string) is required.' });
}
try {
// 1. Embed the user's natural language query
const queryEmbedding = await getEmbedding(query);
// 2. Call the Supabase RPC function for vector similarity search
const { data, error } = await supabase.rpc('match_properties', {
query_embedding: queryEmbedding,
match_count: limit,
filter_bedrooms: bedrooms ?? null,
filter_max_price: max_price ?? null,
filter_city: city ?? null,
filter_listing_type: listing_type ?? null,
});
if (error) {
console.error('Supabase RPC error:', error.message);
return res.status(500).json({ error: error.message });
}
return res.json({ results: data });
} catch (err) {
console.error('Search error:', err.message);
return res.status(500).json({ error: err.message });
}
});
// ─── Start Server ─────────────────────────────────────────────────────────────
const PORT = parseInt(process.env.PORT) || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});