Skip to content

Commit

Permalink
feat(author-search): ♻️ use FlexSearch to return author results
Browse files Browse the repository at this point in the history
  • Loading branch information
djdembeck committed Oct 5, 2021
1 parent 16dad98 commit 92dec92
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 15 deletions.
25 changes: 24 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"fastify": "^3.22.0",
"fastify-plugin": "^3.0.0",
"fastify-redis": "^4.3.2",
"flexsearch": "^0.7.21",
"html-to-text": "^8.0.0",
"isomorphic-fetch": "^3.0.0",
"jsrsasign": "^10.4.1",
Expand All @@ -40,6 +41,7 @@
"typescript": "^4.4.3"
},
"devDependencies": {
"@types/flexsearch": "^0.7.1",
"@types/html-to-text": "^8.0.1",
"@types/isomorphic-fetch": "^0.0.35",
"@types/jest": "^27.0.2",
Expand Down
41 changes: 27 additions & 14 deletions src/config/routes/authors/search/show.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,46 @@
import SharedHelper from '../../../../helpers/shared'
import Author from '../../../models/Author'
// Search
import { Document } from 'flexsearch'

const index = new Document({
document: {
id: 'asin',
index: ['name']
},
preset: 'score'
})

async function routes (fastify, options) {
fastify.get('/authors', async (request, reply) => {
const asin = request.query.asin
const name = request.query.name

if (!name && !asin) {
if (!name) {
throw new Error('No search params provided')
}

if (asin) {
// First, check ASIN validity
const commonHelpers = new SharedHelper()
if (!commonHelpers.checkAsinValidity(asin)) {
throw new Error('Bad ASIN')
}
return Promise.resolve(Author.findOne({ asin: asin }))
}

// Use regular text search until weighted available:
// https://github.com/plexinc/papr/issues/98
if (name) {
return Promise.resolve(
// Find all results of name
const seardDbByName = await Promise.resolve(
Author.find(
{ $text: { $search: name } }
)
)
// Add results to FlexSearch index
seardDbByName.forEach(result => {
index.add(result)
})
// Resulting search
const matchedResults = index.search(name)[0].result as string[]
// Search documents matched by FlexSearch
const found = await Promise.resolve(
Author.find(
{ $text: { $search: `"${name}"` } },
{ limit: 25 }
{ asin: { $in: matchedResults } }
)
)
return found
}
})
}
Expand Down

0 comments on commit 92dec92

Please sign in to comment.