Skip to content

Commit

Permalink
Use mongoose
Browse files Browse the repository at this point in the history
  • Loading branch information
yagop committed Feb 25, 2020
1 parent 72d85d1 commit 1ff3a9a
Show file tree
Hide file tree
Showing 5 changed files with 234 additions and 39 deletions.
18 changes: 18 additions & 0 deletions api/init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { User } = require('../lib/db');

module.exports = async (req, res) => {
const found = await User.findOne({ name: 'Rodrigo' });

if (!found) {
const rodrigo = new User({
name: 'Rodrigo',
life: 100,
toxicity: 0,
potions: 0,
});
const resp = await rodrigo.save();
res.status(201).send('User Rodrigo created. %j', resp);
} else {
res.status(201).send('User rodrigo already exists. %j', found);
}
};
46 changes: 14 additions & 32 deletions lib/db.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,19 @@
const Redis = require("ioredis");
const mongoose = require('mongoose');

const redis = new Redis({
port: process.env.REDIS_PORT,
host: process.env.REDIS_HOST,
password: process.env.REDIS_PASS,
db: process.env.REDIS_DB,
mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

// Inizialize DB
const toxicity = redis.exists(redis, 'rodrigo:toxicity');
if (!toxicity) { // 0
redis.set('rodrigo:toxicity', '0');
}
const life = redis.exists(redis, 'rodrigo:life');
if (!life) { // 0
redis.set('rodrigo:life', '100');
}
const potions = redis.exists(redis, 'rodrigo:potions');
if (!potions) { // 0
redis.set('rodrigo:potions', '0');
}
const User = mongoose.model('User', {
name: String,
life: Number,
toxicity: Number,
potions: Number,
// TODO: Id, index
});

module.exports = {
redis,
quit: (redis) => {
redis.quit();
},

get: async (redis, key) => {
return redis.get(key);
},

set: async (redis, key, value) => {
return redis.set(key, value);
}
}
User,
mongoose,
};
5 changes: 1 addition & 4 deletions now.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
{
"version": 2,
"env": {
"REDIS_HOST": "@redislabs-db-30m-1-host",
"REDIS_PORT": "@redislabs-db-30m-1-port",
"REDIS_DB": "0",
"REDIS_PASS": "@redislabs-db-30m-1-pass",
"MONGO_URL": "@toxic-rpg-bot-mongo-url",
"TG_TOKEN": "@toxic-rpg-bot-token"
},
"regions": ["bru1"],
Expand Down
Loading

1 comment on commit 1ff3a9a

@vercel
Copy link

@vercel vercel bot commented on 1ff3a9a Feb 25, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.