Skip to content

Commit

Permalink
Fix code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
namanyayg committed Jan 8, 2024
1 parent 41b359c commit 714f008
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions _posts/2018-10-13-simple-search-with-like-in-mysql-sequelize.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,20 @@ tags:
A simple way to implement a “search” feature into your node app is using the database engine to check for presence of tokenized search query. In my case, I’m using MySQL with the Sequelize ORM and needed to add a e-commerce like search form with product results for a client.

```js
// sanitize plain text query to only keep alphanumeric lowercase
const sanitizedQuery = query.trim().toLowerCase().replace(/[\W_]+/, '')
// split by space as basic tokenization
const queryTokens = sanitizedQuery.split(/\s+/)
// sanitize plain text query to only keep alphanumeric lowercase
const sanitizedQuery = query.trim().toLowerCase().replace(/[\W_]+/, '')
// split by space as basic tokenization
const queryTokens = sanitizedQuery.split(/\s+/)

const options = {
where: {
[Op.and]: queryTokens.map(token =>
// check for presence of each token in lowercased product `title`
Sequelize.where(Sequelize.fn('lower', Sequelize.col('title')), 'LIKE', `%${token}%`)
)
}
const options = {
where: {
[Op.and]: queryTokens.map(token =>
// check for presence of each token in lowercased product `title`
Sequelize.where(Sequelize.fn('lower', Sequelize.col('title')), 'LIKE', `%${token}%`)
)
}
const results = await db.Product.FindAll(options)
}
const results = await db.Product.FindAll(options)
```

The main `cleverness` of this snippet is in mapping the `queryTokens` to generate `Sequelize.where()` queries that compare the lowercased title with our token. Sequelize has some powerful features to interact with the database at a low-level, and this is a great example of that used in a real-world project

0 comments on commit 714f008

Please sign in to comment.