This repository has been archived on 2021-11-25. You can view files and clone it, but cannot push or open issues or pull requests.
DBHomework/search.cpp
2017-11-19 14:48:41 +08:00

148 lines
5.1 KiB
C++

#include "Request.h"
#include "Response.h"
#include "Util.h"
#include "json.hpp"
using namespace std;
using json=nlohmann::json;
int main()
{
Request req;
Response res;
json j;
auto jsonfail=[&](int errcode,const std::string& errmsg)
{
j["success"]=0;
j["errcode"]=errcode;
j["errmsg"]=errmsg;
};
if(req.requestMethod=="GET")
{
if(req.get["type"].empty())
{
jsonfail(2,"Missing Parameter: type");
}
else
{
string searchType=req.get["type"];
if(searchType=="0")
{
/// Search User
if(req.get["name"].empty())
{
jsonfail(3,"Missing Parameter: name");
}
else
{
/// Search User by ONLY nickname.
string nickname=req.get["name"];
DBInfo db;
if(db.readConfig()<0)
{
/// Failed to read config. May be not installed.
jsonfail(4,"Failed to read configure.");
}
else
{
MySQLConn conn;
if(db.connectProxy(conn)<0)
{
jsonfail(5,"Failed to connect DB");
}
else
{
vector<pair<string,string>> vec;
if(conn.exec(make_str("select name from bs_user where nickname like '%",nickname,"%'"),[&](MySQLResult& res)
{
res.stepRow([&](char** val,unsigned long* len)
{
vec.push_back(make_pair(val[0],val[1]));
});
})<0)
{
jsonfail(6,"Failed to execute SQL.");
}
else
{
j["success"]=1;
int sz=vec.size();
for(int i=0;i<sz;i++)
{
j["result"][i]["uname"]=vec[i].first;
j["result"][i]["nickname"]=vec[i].second;
}
}
}
}
}
}
else if(searchType=="1")
{
/// Search Book
if(req.get["name"].empty())
{
jsonfail(13,"Missing parameter: name");
}
else
{
/// Search book by name
string bookname=req.get["name"];
DBInfo db;
if(db.readConfig()<0)
{
jsonfail(14,"Failed to read configure.");
}
else
{
MySQLConn conn;
if(db.connectProxy(conn)<0)
{
jsonfail(15,"Failed to connect DB");
}
else
{
vector<pair<string,string>> vec;
if(conn.exec(make_str("select class_id,name from bs_book where name like '%",bookname,"%'"),[&](MySQLResult& res)
{
res.stepRow([&](char** val,unsigned long* len)
{
vec.push_back(make_pair(val[0],val[1]));
});
})<0)
{
jsonfail(16,"Failed to execute SQL.");
}
else
{
j["success"]=1;
int sz=vec.size();
for(int i=0;i<sz;i++)
{
j["result"][i]["class_id"]=vec[i].first;
j["result"][i]["name"]=vec[i].second;
}
}
}
}
}
}
else
{
jsonfail(90,"Unknown Type");
}
}
}
else
{
j["success"]=0;
j["errcode"]=1;
j["errmsg"]=make_str("Request Method Not Supported");
}
res.content.append(j.dump());
res.show();
return 0;
}