Skip to content

Commit

Permalink
Added Chat example with async/await
Browse files Browse the repository at this point in the history
  • Loading branch information
wolf4ood committed Nov 6, 2018
1 parent cf1c716 commit 35ce694
Show file tree
Hide file tree
Showing 7 changed files with 4,366 additions and 0 deletions.
1 change: 1 addition & 0 deletions orientjs-chat-example-async-await/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
38 changes: 38 additions & 0 deletions orientjs-chat-example-async-await/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# OrientJS Chat Example

This chat example is a modified version of the official [Socket.io](http://socket.io/get-started/chat/)chat. It shows how to use new OrientJS APIs in an Express.js application + Socket.io

## Quick Start

Run it locally

### Database Setup

* Download [OrientDB](https://orientdb.com/download-2/) v3.0.x
* Start it locally
* Create a database `chat`
* Open Studio (http://localhost:2424)
* Create a class `Room` (`create class Room`)


### App Setup

Clone this project from Github

Install dependencies

```
$ npm install
```

Run the application

```
$ npm start
```

Go to

```
http://localhost:3000/
```
22 changes: 22 additions & 0 deletions orientjs-chat-example-async-await/app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "Socket-Chat-Example",
"description": "my first socket.io app",
"website": "https://github.com/socketio/chat-example",
"repository": "https://github.com/socketio/chat-example",
"logo": "https://node-js-sample.herokuapp.com/node.svg",
"success_url": "/",
"keywords": [
"node",
"express",
"socket.io",
"realtime",
"websocket"
],
"scripts": {
},
"addons": [
],
"env": {
"BUILDPACK_URL": "https://github.com/heroku/heroku-buildpack-nodejs"
}
}
125 changes: 125 additions & 0 deletions orientjs-chat-example-async-await/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<!doctype html>
<html>

<head>
<title>OrientJS Socket.IO chat</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font: 13px Helvetica, Arial;
}

form {
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}

form p {
background-color: white;
padding: 10px;
width: 10%;
display: inline-block;
}

form input {
border: 0;
padding: 10px;
width: 80%;
margin-right: .5%;
}

form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}

#messages {
list-style-type: none;
margin: 0;
padding: 0;
}

#messages li {
padding: 5px 10px;
}

#messages li:nth-child(odd) {
background: #eee;
}

#messages li p.name {
width: 8%;
display: inline-block
}

#messages li p.text {
width: 90%;
display: inline-block;
padding-left: 5px
}

#messages {
margin-bottom: 40px
}
</style>
</head>

<body>
<ul id="messages">

</ul>
<form action="">
<p id="author"></p>
<input id="m" autocomplete="off" />
<button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Faker/3.1.0/faker.min.js"></script>
<script>
$(function () {

var appendMessage = function (msg) {
var elem = $('<li>').append($('<p class="name">').text(msg.author + " >"));
$(elem).append($('<p class="text">').text(msg.text));
$('#messages').append(elem);
};

var initChat = function () {
var socket = io();
var author = faker.name.findName();
$('form').submit(function () {
let msg = { author: author, text: $('#m').val() };
socket.emit('chat message', msg);
$('#m').val('');
return false;
});
$('#author').text("Hi " + author);
socket.on('chat message', function (msg) {
appendMessage(msg);
window.scrollTo(0, document.body.scrollHeight);
});
}
$.get('/messages', (data) => {

data.forEach((msg)=>{
appendMessage(msg);
})
initChat();
})

});
</script>
</body>

</html>
122 changes: 122 additions & 0 deletions orientjs-chat-example-async-await/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
const app = require("express")();
const http = require("http").Server(app);
const io = require("socket.io")(http);
const port = process.env.PORT || 4000;
const OrientDBClient = require("orientjs").OrientDBClient;

const config = {
host: "localhost",
db: "chat",
user: "admin",
password: "admin",
rootUser: "root",
rootPassword: "root"
};
const run = async () => {
let { client, pool } = await setupDatabase();
boostrap({ client, pool });
};

const setupDatabase = async () => {
let client = await OrientDBClient.connect({
host: config.host,
pool: {
max: 10
}
});

let exists = await client.existsDatabase({
name: config.db,
username: config.rootUser,
password: config.rootPassword
});

if (!exists) {
await client.createDatabase({
name: config.db,
username: config.rootUser,
password: config.rootPassword
});
}

let pool = await client.sessions({
name: config.db,
username: config.user,
password: config.password,
pool: {
max: 25
}
});

let session = await pool.acquire();
await session.command("create class Room IF NOT EXISTS extends V").one();
await session.close();
return { client, pool };
};

const startLiveQuery = async pool => {
let session = await pool.acquire();

session.liveQuery(`select from Room`).on("data", msg => {
// inserted record op = 1
if (msg.operation === 1) {
io.emit("chat message", msg.data);
}
});
await session.close();
};

const listenForMessage = pool => {
io.on("connection", function(socket) {
socket.on("chat message", async msg => {
let session = await pool.acquire();
try {
session
.command(
`insert into Room set text = :text, date = sysdate(), author = :author`,
{ params: msg }
)
.one();
} catch (ex) {
console.log(ex);
}
});
});
};
const boostrap = ({ client, pool }) => {
startLiveQuery(pool);
listenForMessage(pool);

app.use(async (req, res, next) => {
try {
let session = await pool.acquire();
res.locals.db = session;
res.on("finish", async () => {
await session.close();
});
next();
} catch (ex) {
res.status(500).send(err);
}
});
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});

app.get("/messages", async (req, res) => {
try {
let messages = await res.locals.db
.query("select from Room order by date limit 20")
.all();
res.send(messages);
} catch (err) {
res.status(500).send(err);
}
});

http.listen(port, function() {
console.log("listening on *:" + port);
});
};

run();
Loading

0 comments on commit 35ce694

Please sign in to comment.