Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Live search using socket.io

How can I create live search using socket.io?

I use RethinkDB + Node + Express + Socket.io + Redux + React, I am listening to event (it is changefeed created using rethinkdb), which sends me lets say 10 items on client side and displaying them using react.

Now I want to create live search, which sends query to server, searches for results in DB, returns first 10 results and sends them to client with socket.io

// emit events for changes

r.table('stackoverflow_questions')
.changes({ includeInitial: true, squash: true })
.limit(10)
.run(connection)
.then(changefeedSocketEvents(socket, 'topic'))

-

// Socket.io events for changefeed

module.exports = function (socket, entityName) {
  return function (rows) {
    rows.each(function (err, row) {
      if (err) { return console.log(err) } else if (row.new_val && !row.old_val) {
        socket.emit(entityName + ':insert', row.new_val)
      } else if (row.new_val && row.old_val) {
        socket.emit(entityName + ':update', row.new_val)
      } else if (row.old_val && !row.new_val) {
        socket.emit(entityName + ':delete', { id: row.old_val.id })
      }
    })
  }
}

I don't have Idea how you can achieve that using socket.io, do you have to create custom socket event listeners on the fly for every custom query? (It sounds ridiculous to me, I think, that there should be a simple way)

like image 867
stpoa Avatar asked Jul 12 '26 09:07

stpoa


1 Answers

I found a solution, here is a bare minimum example:

// server.js

const express = require('express')
const app = express()
const http = require('http')
const server = http.Server(app)
const io = require('socket.io')(server)

app.use(express.static('client'))

io.on('connection', function(client){
    setInterval(() => io.emit('found', 'dfasdfadsfasdfasdf'), 5000)
    console.log('connected with socket: ' + client.id)
client.on('search', function (text) {
    const data = Math.random()
    io.emit('found', data + text)
})
client.on('disconnect', function(){})
})

app.get('/')

server.listen(3000)

-

<!- index.html ->

<!DOCTYPE html>
<html>
<head>
  <script src="/socket.io/socket.io.js"></script>
  <script src="./client.js"></script>
  <title>socket-io-live-search</title>
</head>
<body>
  <div id='search'>
    <input type ='text' />
  </div>
</body>
</html>

-

// client.js

var socket = io()

const loaded = () => {
    const inputEl = document.querySelector('#search input')
    inputEl.oninput = (e) => socket.emit('search', e.target.value)
}

socket.on('found', (data) => console.log('found: ' + data))

document.addEventListener('DOMContentLoaded', loaded, false)
like image 163
stpoa Avatar answered Jul 13 '26 23:07

stpoa