Commit 827cd3d9 authored by Geovera's avatar Geovera

First iteration of database. Insert/modify/get unit. User model and route base

parents

Too many changes to show.

To preserve performance only 334 of 334+ files are displayed.

# cbdiscord
#!/bin/bash
#
# Script to create MySQL db + user
#
# @author Raj KB <magepsycho@gmail.com>
# @website http://www.magepsycho.com
# @version 0.1.0
################################################################################
# CORE FUNCTIONS - Do not edit
################################################################################
#
# VARIABLES
#
_bold=$(tput bold)
_underline=$(tput sgr 0 1)
_reset=$(tput sgr0)
_purple=$(tput setaf 171)
_red=$(tput setaf 1)
_green=$(tput setaf 76)
_tan=$(tput setaf 3)
_blue=$(tput setaf 38)
#
# HEADERS & LOGGING
#
function _debug()
{
[ "$DEBUG" -eq 1 ] && $@
}
function _header()
{
printf "\n${_bold}${_purple}========== %s ==========${_reset}\n" "$@"
}
function _arrow()
{
printf "➜ $@\n"
}
function _success()
{
printf "${_green}✔ %s${_reset}\n" "$@"
}
function _error() {
printf "${_red}✖ %s${_reset}\n" "$@"
}
function _warning()
{
printf "${_tan}➜ %s${_reset}\n" "$@"
}
function _underline()
{
printf "${_underline}${_bold}%s${_reset}\n" "$@"
}
function _bold()
{
printf "${_bold}%s${_reset}\n" "$@"
}
function _note()
{
printf "${_underline}${_bold}${_blue}Note:${_reset} ${_blue}%s${_reset}\n" "$@"
}
function _die()
{
_error "$@"
exit 1
}
function _safeExit()
{
exit 0
}
#
# UTILITY HELPER
#
function _seekConfirmation()
{
printf "\n${_bold}$@${_reset}"
read -p " (y/n) " -n 1
printf "\n"
}
# Test whether the result of an 'ask' is a confirmation
function _isConfirmed()
{
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
return 0
fi
return 1
}
function _typeExists()
{
if [ $(type -P $1) ]; then
return 0
fi
return 1
}
function _isOs()
{
if [[ "${OSTYPE}" == $1* ]]; then
return 0
fi
return 1
}
function _checkRootUser()
{
#if [ "$(id -u)" != "0" ]; then
if [ "$(whoami)" != 'root' ]; then
echo "You have no permission to run $0 as non-root user. Use sudo"
exit 1;
fi
}
function _printPoweredBy()
{
cat <<"EOF"
Powered By:
__ ___ ___ __
/ |/ /__ ____ ____ / _ \___ __ ______/ / ___
/ /|_/ / _ `/ _ `/ -_) ___(_-</ // / __/ _ \/ _ \
/_/ /_/\_,_/\_, /\__/_/ /___/\_, /\__/_//_/\___/
/___/ /___/
>> Store: http://www.magepsycho.com
>> Blog: http://www.blog.magepsycho.com
################################################################
EOF
}
################################################################################
# SCRIPT FUNCTIONS
################################################################################
function generatePassword()
{
echo "$(openssl rand -base64 12)"
}
function _printUsage()
{
echo -n "$(basename $0) [OPTION]...
Create MySQL db & user.
Version $VERSION
Options:
-h, --host MySQL Host
-d, --database MySQL Database
-u, --user MySQL User
-p, --pass MySQL Password (If empty, auto-generated)
-h, --help Display this help and exit
-v, --version Output version information and exit
Examples:
$(basename $0) --help
"
_printPoweredBy
exit 1
}
function processArgs()
{
# Parse Arguments
for arg in "$@"
do
case $arg in
-h=*|--host=*)
DB_HOST="${arg#*=}"
;;
-d=*|--database=*)
DB_NAME="${arg#*=}"
;;
-u=*|--user=*)
DB_USER="${arg#*=}"
;;
-p=*|--pass=*)
DB_PASS="${arg#*=}"
;;
--debug)
DEBUG=1
;;
-h|--help)
_printUsage
;;
*)
_printUsage
;;
esac
done
[[ -z $DB_NAME ]] && _error "Database name cannot be empty." && exit 1
[[ $DB_USER ]] || DB_USER=$DB_NAME
}
function createMysqlDbUser()
{
SQL1="CREATE DATABASE IF NOT EXISTS ${DB_NAME};"
SQL2="CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '${DB_PASS}';"
SQL3="GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%';"
SQL4="FLUSH PRIVILEGES;"
SQL5="CREATE TABLE units(
id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
name CHAR(30) NOT NULL,
type CHAR(15) NOT NULL,
stars tinyint unsigned,
hp mediumint unsigned,
pap mediumint unsigned,
pd mediumint unsigned,
sap mediumint unsigned,
sd mediumint unsigned,
bap mediumint unsigned,
bp mediumint unsigned,
pdf mediumint unsigned,
sdf mediumint unsigned,
bdf mediumint unsigned,
leadership smallint unsigned,
troop_count tinyint unsigned,
hero_level tinyint unsigned);"
SQL6="CREATE TABLE houses(
id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
house_name CHAR(30) NOT NULL);"
SQL7="CREATE TABLE users(
id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
discord_id CHAR(30) NOT NULL,
house_id bigint unsigned,
leadership smallint unsigned,
FOREIGN KEY(house_id) REFERENCES houses(id));"
SQL8="CREATE TABLE house_role_lk(
lk_key CHAR(3) NOT NULL PRIMARY KEY,
lk_name CHAR(30) NOT NULL,
lk_desc CHAR(50),
lk_permission_level tinyint unsigned);"
SQL9="CREATE TABLE users_houses(
user_id bigint unsigned NOT NULL,
house_id bigint unsigned NOT NULL,
role_lk CHAR(3) NOT NULL,
PRIMARY KEY(user_id, house_id),
FOREIGN KEY(user_id) REFERENCES users(id),
FOREIGN KEY(house_id) REFERENCES houses(id),
FOREIGN KEY(role_lk) REFERENCES house_role_lk(lk_key));"
SQL10="CREATE TABLE users_units(
user_id bigint unsigned NOT NULL,
unit_id bigint unsigned NOT NULL,
unit_level tinyint unsigned,
elite_flg boolean not null default 0,
PRIMARY KEY(user_id, unit_id),
FOREIGN KEY(user_id) REFERENCES users(id),
FOREIGN KEY(unit_id) REFERENCES units(id));"
SQL11="CREATE TABLE users_units(
user_id bigint unsigned NOT NULL,
unit_level tinyint unsigned,
PRIMARY KEY(user_id));"
# FOREIGN KEY(user_id) REFERENCES users(id),
# FOREIGN KEY(unit_id) REFERENCES units(id));"
if [ -f /root/.my.cnf ]; then
$BIN_MYSQL -e "${SQL1}${SQL2}${SQL3}${SQL4}"
else
# If /root/.my.cnf doesn't exist then it'll ask for root password
_arrow "Please enter root user MySQL password!"
read rootPassword
$BIN_MYSQL -h $DB_HOST -u root -p${rootPassword} -e "${SQL1}${SQL2}${SQL3}${SQL4}"
#$BIN_MYSQL -u root -p${rootPassword} -e "${SQL1}"
$BIN_MYSQL -u root -p${rootPassword} ${DB_NAME} -e "${SQL5}${SQL6}${SQL7}${SQL8}${SQL9}${SQL10}"
fi
}
function printSuccessMessage()
{
_success "MySQL DB / User creation completed!"
echo "################################################################"
echo ""
echo " >> Host : ${DB_HOST}"
echo " >> Database : ${DB_NAME}"
echo " >> User : ${DB_USER}"
echo " >> Pass : ${DB_PASS}"
echo ""
echo "################################################################"
_printPoweredBy
}
################################################################################
# Main
################################################################################
export LC_CTYPE=C
export LANG=C
DEBUG=0 # 1|0
_debug set -x
VERSION="0.1.0"
BIN_MYSQL=$(which mysql)
DB_HOST='localhost'
DB_NAME=
DB_USER=
DB_PASS=$(generatePassword)
function main()
{
[[ $# -lt 1 ]] && _printUsage
_success "Processing arguments..."
processArgs "$@"
_success "Done!"
_success "Creating MySQL db and user..."
createMysqlDbUser
_success "Done!"
printSuccessMessage
exit 0
}
main "$@"
_debug set +x
DBNAME=$1
USERDB=$2
PASSDB=$3
./deleteDatabase.sh ${DBNAME} ${USERDB} ${PASSDB}
./createDatabase.sh -d=${DBNAME} -u=${USERDB} -p=${PASSDB}
DBNAME=$1
USERDB=$2
PASSDB=$3
mysql -u ${USER} -p${PASSDB} -e "DROP DATABASE ${DBNAME};"
apt-get install python3 -y
apt-get install python3-pip -y
apt-get install mysql-server -y
apt-get install mysql-client -y
apt-get install mysql-common -y
{
"host": "localhost",
"user": "root",
"password": "goodyear",
"database": "conquerors_blade_db",
"connectionLimit": 100
}
\ No newline at end of file
const fs = require('fs');
const MySQL = require('promise-mysql');
let config_file = fs.readFileSync('./database/config.json');
let db_config = JSON.parse(config_file);
const db = {}
let connection = MySQL.createConnection(db_config);
connection.then((con) =>{
console.log('Database Connected');
db.con = con;
});
module.exports = db;
\ No newline at end of file
const Koa = require('koa');
const bodyParser = require('koa-body');
const unitsRouter = require('./routes/units');
const app = new Koa();
app.use(bodyParser());
app.use(unitsRouter.routes()).use(unitsRouter.allowedMethods());
app.listen(3000, () => console.log('Server Started'));
\ No newline at end of file
const db = require('../database/database');
const units = {};
const unit_columns = ['name', 'type', 'stars', 'hp', 'pap', 'pd', 'sap', 'sd', 'bap', 'bp', 'pdf', 'sdf', 'bdf', 'leadership', 'troop_count', 'hero_level'];
units.getAll = async (context) =>{
let sql_text = 'SELECT * FROM units';
try{
let data = await db.con.query(sql_text);
return {units: data};
}catch(error){
console.log(error);
context.throw(400, 'INVALID_DATA');
}
}
units.getUnit = async (context, id) =>{
let sql_text = `SELECT * FROM units WHERE id=${id}`;
try{
let data = await db.con.query(sql_text);
return {unit: data};
}catch(error){
console.log(error);
context.throw(400, 'INVALID_DATA');
}
}
units.insertUnit = async (context, body) =>{
let column_text = 'name, type';
let value_text = `'${body.name}', '${body.type}'`;
for (let i = 2; i < unit_columns.length; i++) {
const element = unit_columns[i];
if(body[element]){
column_text += ', ' + element;
value_text += ', ' +body[element];
}
}
let sql_query = 'INSERT INTO units (' + column_text + ') VALUES (' + value_text + ');';
try{
let data = await db.con.query(sql_query);
return {status: 'success'};
}catch(error){
console.log(error);
context.throw(400, 'INVALID_DATA');
}
}
units.modifyUnit = async (context, body) => {
let set_text = '';
if(body.name && body.type){
set_text += `name = '${body.name}' type = '${body.type}'`;
}else if(body.name){
set_text += `name = '${body.name}'`;
}else if(body.type){
set_text += `type = '${body.type}'`;
}
for (let i = 2; i < unit_columns.length; i++) {
const element = unit_columns[i];
if(set_text===''){
set_text = `${element} = ${body[element]}`;
}else if(body[element]){
set_text = `, ${element} = ${body[element]}`;
}
}
let sql_query = `UPDATE units SET ${set_text} WHERE id = ${body.id}`;
try{
let data = await db.con.query(sql_query);
return {status: 'success'};
}catch(error){
console.log(error);
context.throw(400, 'INVALID_DATA');
}
}
module.exports = units;
\ No newline at end of file
const db = require('../database/database');
const users = {};
module.exports = users;
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2015 Alexander C. Mingoia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# @koa/router
Router middleware for [koa](https://github.com/koajs/koa)
[![NPM version](https://img.shields.io/npm/v/@koa/router.svg?style=flat)](https://npmjs.org/package/@koa/router)
[![NPM Downloads](https://img.shields.io/npm/dm/@koa/router.svg?style=flat)](https://npmjs.org/package/@koa/router)
[![Node.js Version](https://img.shields.io/node/v/@koa/router.svg?style=flat)](http://nodejs.org/download/)
[![Build Status](https://img.shields.io/travis/koajs/router.svg?style=flat)](http://travis-ci.org/koajs/router)
[![gitter](https://img.shields.io/gitter/room/koajs/koa.svg?style=flat)](https://gitter.im/koajs/koa)
* Express-style routing (`app.get`, `app.put`, `app.post`, etc.)
* Named URL parameters
* Named routes with URL generation
* Responds to `OPTIONS` requests with allowed methods
* Support for `405 Method Not Allowed` and `501 Not Implemented`
* Multiple route middleware
* Multiple and nestable routers
* `async/await` support
## Migrating to 7 / Koa 2
- The API has changed to match the new promise-based middleware
signature of koa 2. See the
[koa 2.x readme](https://github.com/koajs/koa/tree/2.0.0-alpha.3) for more
information.
- Middleware is now always run in the order declared by `.use()` (or `.get()`,
etc.), which matches Express 4 API.
## Installation
Install using [npm](https://www.npmjs.org/):
```sh
npm install @koa/router
```
## [API Reference](./API.md)
## Contributing
Please submit all issues and pull requests to the [koajs/router](http://github.com/koajs/router) repository!
## Tests
Run tests using `npm test`.
## Support
If you have any problem or suggestion please open an issue [here](https://github.com/koajs/router/issues).
## Call for Maintainers
This module is forked from the original [koa-router](https://github.com/ZijianHe/koa-router) due to its lack of activity. `koa-router` is the most widely used router module in the Koa community and we need maintainers. If you're interested in fixing bugs or implementing new features feel free to open a pull request. We'll be adding active contributors as collaborators.
Thanks to the original authors @alexmingoia and the original team for their great work.
8.0.0 / 2019-06-16
==================