Skip to content

Commit

Permalink
[+Add] Adding tests
Browse files Browse the repository at this point in the history
[+Add]  Adding readme
[+Add]  Adding helmet
[*Feat] Fixing some issue with main services
[-Delete] Delete logs
  • Loading branch information
mohammadhb committed Apr 14, 2021
1 parent 8e02d9a commit 7ed05f6
Show file tree
Hide file tree
Showing 17 changed files with 449 additions and 158 deletions.
57 changes: 56 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,57 @@
# Messenger
A Simple Messenger
## A Simple Facebook Bot Messenger

<img alt="Sample demo of The Messenger Bot" src="./example.gif" width="270" height="480">

### Installation:

- Install required packages
```shell script
npm i
```
- Copy and modify .env file for Environment Variables
```shell script
cp .env.example .env
```

### Configuration
- Put the Access Token in the `MESSENGER_BOT_ACCESS_TOKEN` in `.env` file
- Put the Verify Token in the `MESSENGER_BOT_VERIFY_TOKEN` in `.env` file

### Usage

Run the project
```shell script
npm start
```

For the development perposes
```shell script
npm i -g nodemon
npm run dev
```

For the deployment perposes
```shell script
docker-compose up -d
```


### Tests

Run the tests
```shell script
npm test
```

For coverage run
```shell script
npm run coverage
```

### Documents

For generate and serve documents
```shell script
npm run doc
```
24 changes: 9 additions & 15 deletions controller/conversation.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ async function event(request,response){
for (let entry of body.entry){

const event = entry.messaging[0];
console.log(event);


//Save any incoming messages
new Message({
Expand All @@ -26,37 +24,33 @@ async function event(request,response){
timestamp:event.timestamp
}).save();

console.log(event);

let userCache = await cacheUtil.getUserFromCache(event.sender.id),
user;

if(!userCache.user) {

if(userCache.user){
// console.log(userCache.user);
// console.log(userCache.status);
user = userCache;
}else {
user = await new User().getById(event.sender.id);
if(!user){
user = await new User({
id:event.sender.id
}).save();
}
userCache.user = user;

userCache.user = {
firstname:user.firstname,
birthdate:user.birthdate
};

}

//Sending User to Main Service

await mainService(user,event.message.text);
await mainService(user,userCache,event.message.text);

response.status(200).send("EVENT_RECEIVED");

}




} else {

response.sendStatus(404);
Expand Down
1 change: 0 additions & 1 deletion database/mongodb/models/user.model.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const mongoose = require("mongoose");

const Schema = mongoose.Schema;
const Types = Schema.Types;

const modelName = "User";
const collection = "users";
Expand Down
2 changes: 0 additions & 2 deletions database/postgresql/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ fs.readdirSync(modelPath)
return file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js";
})
.forEach((file) => {
console.log("__dirname", require(path.join(modelPath, file)));
const model = require(path.join(modelPath, file))(sequelize, Sequelize.DataTypes);
console.log(modelPath,file);
db[model.name] = model;
});

Expand Down
4 changes: 2 additions & 2 deletions database/redis/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class Redis {
async closeConnection(){

for (const client of this._clients){
await client.sendCommand("FLUSHALL");
await client.end(true);
}

Expand Down Expand Up @@ -55,13 +56,12 @@ class Redis {

async createClient(dbNum){

return new Promise((resolve,reject)=>{
return new Promise((resolve)=>{

let client = redis.createClient();

client.select(dbNum,()=>{

console.log(`Redis started DBNUM=${dbNum}`);
resolve(client);

});
Expand Down
87 changes: 37 additions & 50 deletions database/redis/models/cache.model.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,40 @@
class Model {

constructor(client){

this.cache = {};

this.client = client;
this.expireTime = 60*60*2;//2h

}

async readFromCache(key){

// const data = JSON.stringify(value);
// return this.client.getAsync(key,data,'EX',this.expireTime);

return new Promise((
(resolve)=>{

let result;

if(!this.cache[key]){
try{
result = await this.client.getAsync(key,data,'EX',this.expireTime);
}catch(error){
throw new Error("Couldn't read from Cache");
}
} else {
result = this.cache[key];
}

resolve(result)

},
(reject)=>{

}
))

}

updateCache(key,value){

this.data[key] = value;
const data = JSON.stringify(value);
return this.client.setAsync(key,data,'EX',this.expireTime);

}


constructor(client) {
this.cache = {};

this.client = client;
this.expireTime = 60 * 60 * 2; //2h
}

async readFromCache(key) {
// const data = JSON.stringify(value);
// return this.client.getAsync(key,data,'EX',this.expireTime);

return new Promise(
((resolve) => {
let result;

if (!this.cache[key]) {
try {
result = this.client.get(key);
} catch (error) {
throw new Error("Couldn't read from Cache");
}
} else {
result = this.cache[key];
}

resolve(result);
},
() => {})
);
}

updateCache(key, value) {
this.data[key] = value;
const data = JSON.stringify(value);
return this.client.setAsync(key, data, "EX", this.expireTime);
}
}

module.exports = Model;
module.exports = Model;
33 changes: 18 additions & 15 deletions database/redis/models/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class Model {
this.dataClient = dataClient;

this._status = null;
this.user = {};
this._user = null;

this.expireTime = 60*60*2;//2h

Expand All @@ -19,22 +19,14 @@ class Model {

if(value){

console.log("setting user",this.user);

if(this.user){
this.user.firstname = value;
}else {
this.user = {
firstname:value
};
}

console.log({
id:this.id,
firstname:this.user.firstname,
...this.user
});


this.dataClient.set(
this.id,
JSON.stringify({
Expand Down Expand Up @@ -77,25 +69,36 @@ class Model {

async setId(value){

console.log("setId",value);

if(value){

this.id=value;
this.user = JSON.parse(await this.dataClient.getAsync(value));
this._user = JSON.parse(await this.dataClient.getAsync(value));
this._status = await this.statusClient.getAsync(value);

}

}

get user(){
return this._user;
}

set user(value){
this._user=value;
}

async init(id,user){

this.id=id;
this._user=user;

}

get status(){
return this._status;
}
set status(value){

console.log("status",this.id,value);

this._status = value;
this.statusClient.set(
this.id,
Expand Down
Binary file added example.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 0 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ try{

}catch(error){

console.log(error);
//Error on Listening
process.exit(0);

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "0.0.1",
"description": "A Simple Messenger Bot",
"main": "index.js",
"private":true,
"scripts": {
"start": "node index.js",
"doc": "swagger-jsdoc -d ./swagger.config.js -o ./swagger.json './database/mongodb/models/**/*.js' './controller/**/*.js' && redoc-cli serve ./swagger.json",
Expand All @@ -19,7 +20,7 @@
"facebook"
],
"author": "Mohammad Hosein Balkhani",
"license": "ISC",
"license": "MIT",
"dependencies": {
"axios": "^0.21.1",
"bluebird": "^3.7.2",
Expand Down
2 changes: 0 additions & 2 deletions requests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ function sendMessage(recipient, message, quickReplies) {
params: { access_token },
};

console.log(data);

return client.post(path, data, options);
}

Expand Down
3 changes: 2 additions & 1 deletion router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ const
router.use("/conversations",require("./conversation"));
router.use("/messages",require("./message"));

router.use(require("helmet"));
router.use(require("helmet")());

/* istanbul ignore next */
function start(port) {

if(!port){
Expand Down
Loading

0 comments on commit 7ed05f6

Please sign in to comment.