Skip to content

Instantly share code, notes, and snippets.

@joeywhelan
Created November 5, 2023 18:43
Express.js route for searching the rental properties
app.post('/property/search', async (req, res) => {
const { type, zip, radius, begin, end } = req.body;
console.log(`app - POST /property/search ${JSON.stringify(req.body)}`);
try {
const loc = await client.get(`zip:${zip}`);
if (!loc) {
throw new Error('Zip code not found');
}
const query = `@type:{${type}} @coords:[${loc} ${radius} mi]`;
const docs = await client.ft.aggregate('propIdx', query,
{
DIALECT: 3,
LOAD: [
'@__key',
{ identifier: `$.availability[?(@.begin<=${begin} && @.end>=${end})]`,
AS: 'match'
}
],
STEPS: [
{ type: AggregateSteps.FILTER,
expression: 'exists(@match)'
},
{
type: AggregateSteps.SORTBY,
BY: {
BY: '@rate',
DIRECTION: 'ASC'
}
},
{
type: AggregateSteps.LIMIT,
from: 0,
size: 3
}
]
});
if (docs && docs.results) {
let properties = [];
for (const result of docs.results) {
const rental_date = JSON.parse(result.match);
const property = {
"key": result.__key,
"rate": result.rate,
"begin": rental_date[0].begin,
"end": rental_date[0].end
};
properties.push(property);
}
console.log(`app - POST /property/search - properties found: ${properties.length}`);
res.status(200).json(properties);
}
else {
console.log('app - POST /property/search - no properties found');
res.status(401).send('No properties found');
}
}
catch (err) {
console.log(`app - POST /property/search - error: ${err.message}`);
res.status(400).json({ 'error': err.message });
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment