first commit
This commit is contained in:
93
server/api/address/index.get.ts
Normal file
93
server/api/address/index.get.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { useToString } from '@vueuse/core'
|
||||
export default defineEventHandler(async (event) => {
|
||||
const query = getQuery(event)
|
||||
const keywords = useToString(query.search).value.split(' ')
|
||||
|
||||
function pipelineFilter(keywords) {
|
||||
var result = [{}]
|
||||
keywords.forEach((keyword, index) => {
|
||||
result[index] = {
|
||||
$match: {
|
||||
$or: [
|
||||
{
|
||||
'regencies.districts.villages.name': {
|
||||
$regex: (index === 0 ? '^' : '') + keyword,
|
||||
$options: 'i',
|
||||
},
|
||||
},
|
||||
{
|
||||
'regencies.districts.name': {
|
||||
$regex: (index === 0 ? '^' : '') + keyword,
|
||||
$options: 'i',
|
||||
},
|
||||
},
|
||||
{
|
||||
'regencies.name': {
|
||||
$regex: (index === 0 ? '^(KOTA|KABUPATEN) ' : '') + keyword,
|
||||
$options: 'i',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: {
|
||||
$regex: (index === 0 ? '^' : '') + keyword,
|
||||
$options: 'i',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
try {
|
||||
const results = await prisma.address.aggregateRaw({
|
||||
pipeline: [
|
||||
{ $unwind: { path: '$regencies' } },
|
||||
{ $unwind: { path: '$regencies.districts' } },
|
||||
{
|
||||
$unwind: {
|
||||
path: '$regencies.districts.villages',
|
||||
},
|
||||
},
|
||||
|
||||
...pipelineFilter(keywords),
|
||||
{
|
||||
$limit: 10,
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 1,
|
||||
name: 1,
|
||||
regencies: {
|
||||
_id: 1,
|
||||
name: 1,
|
||||
districts: {
|
||||
_id: 1,
|
||||
name: 1,
|
||||
villages: {
|
||||
_id: 1,
|
||||
name: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
return results.map((result) => {
|
||||
return {
|
||||
_id: 'ID',
|
||||
name: 'INDONESIA',
|
||||
states: result,
|
||||
display: `DESA/KEL ${result.regencies.districts.villages.name} KEC. ${result.regencies.districts.name} ${result.regencies.name} PROVINSI ${result.name}`,
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
// Return error if fetching users fails
|
||||
return {
|
||||
status: 500,
|
||||
body: { message: 'Failed to fetch address' },
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user