반응형
'this'가 있는 함수의 함수에 액세스하는 방법
제 질문은 이것과 비슷합니다.
다만, 제 것은 Node.js로 동작하고 있기 때문에, 조금 더 복잡한 것 같습니다.
서버 쪽은 내가 만든 것이 아니라 내가 연락할 수 없는 다른 사람이 만든 것이다.그리고 그는 매우 다르게 코드를 썼습니다.
그리고 나는 그렇게 했다.db.js
이렇게 생겼죠.
그리고.routes/email.js
사용하고 있다db.js
다음과 같습니다.
그리고 버튼을 클릭했을 때.다음의 에러가 표시됩니다.
db.emailRequest is not a function
에db.js
, 파일 끝에 있습니다.원래 다음과 같은 기능이 있었습니다.
module.exports = new dbHelper;
그리고 내 스타일은db.js
라우터로 설정합니다.
db.get().query(sql, input, function(err,res){
//TODO:
});
하지만 그것은 작동하지 않았다.그래서 마지막을 바꿨어요.db.js
다음과 같습니다.
exports.get = function(){
console.log("exports.get");
return pool;
}
그리고 코드도 추가했습니다.app.js
다음과 같습니다.
db.connect(function(err){
if(err){
console.log('Unable to connect to MariaDB');
process.exit(1);
}
});
어떻게 해야 하나?
의 완전한 코드db.js
다음 항목이 있습니다.
const mariadb = require('mariadb');
var pool;
exports.connect = function(done){
console.log("Trying to connect DB...");
pool = mariadb.createPool({
host: 'localhost',
user: 'root',
password: 'xxxxxxx',
database:"XXXXX",
connectionLimit: 5 // Why 5 ???
});
pool.getConnection()
.then(conn => {
console.log("DB connected. id: " + conn.threadId);
conn.end(); //release to pool
}).catch(err => {
console.log("DB failed connection: " + err);
});
}
function makeToken(){
console.log("makeToken()");
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for(var i=0;i<32;i++){
text+=possible.charAt(Math.floor(Math.random()*possible.length));
}
return text;
}
function dbHelper() {
console.log("dbHelper()");
this.emailRequest = function(email,num){
console.log("emailRequest");
pool.getConnection().then(conn => {
conn.query("INSERT INTO email_verification(email, code) VALUES(?,?)",[email,num]);
conn.end(); //release to pool
})
.catch(err => {
console.log("not connected due to error: " + err);
});
}
// wait and process until getting return value because rv is needed.
this.verify = async function(email,num){
console.log("verify");
let conn;
var result = false;
try {
conn = await pool.getConnection();
// within 3minutes
const rows = await conn.query("SELECT count(*) FROM email_verificaiton WHERE email=? AND code=? AND req_time >= NOW() - INTERVAL 3 MINUTE",[email,num]);
if(rows[0]["count(*)"]>0){
result = true;
}
} catch (err) {
throw err;
} finally {
if (conn) conn.end();
}
return result;
}
this.verifyUpdate = function(email,num){
console.log("verifyUpdate");
pool.getConnection()
.then(conn => {
conn.query("UPDATE email_verification SET status = 1 WHERE email=? AND code=?",[email,num]);
conn.end(); //release to pool
})
.catch(err => {
console.log("not connected due to error: " + err);
});
}
// wait and process until getting return value because rv is needed.
this.emailRegister = async function(email,pass,nick,devid){
console.log("emailRegister");
let conn;
var result;
try {
conn = await pool.getConnection();
var rows = await conn.query("SELECT count(*) FROM email_verification WHERE email=? AND status = 1",[email]);
if(rows[0]["count(*)"]>0){
rows = await conn.query("SELECT count(*) FROM member WHERE email=?",[email]);
if(rows[0]["count(*)"]==0){
var token = makeToken();
rows = await conn.query("INSERT INTO member (email,password,username,device_id,login_method,token) VALUES(?,?,?,?,0,?)",[email,pass,nick,devid,token]);
if(rows["affectedRows"]>0){
result = {result:true, code:200, message: "success",data:[{email:email,token:token}]};
} else{
result = {result:false,code:401, message:"db error"};
}
}else {
result = {result:false,code:402, message:"already registered id"};
}
} else {
result = {result:false,code:403, meesage:"email not verified"};
}
} catch (err) {
throw err;
} finally {
if (conn) conn.end();
}
return result;
}
// wait and process until getting return value because rv is needed.
this.emailLogin = async function(email,pass,devid){
console.log("emailLogin");
let conn;
var result;
try {
conn = await pool.getConnection();
rows = await conn.query("SELECT * FROM member WHERE email=?",[email]);
if(rows.length==1){
if(rows[0]["password"]==pass){
var token = makeToken();
rows = await conn.query("UPDATE member SET device_id = ?, token = ? WHERE email=?",[devid,token,email]);
console.log(rows)
if(rows["affectedRows"]>0){
result = {result:true,message:"Sign up Success.", code:200, data:[{email:email,token:token}]};
} else{
result = {result:false,message:"db error",code:401};
}
} else {
result = {result:false,message:"wrong password",code:402};
}
}else {
result = {result:false,message:"not registered id",code:403};
}
} catch (err) {
throw err;
} finally {
if (conn) conn.end();
}
return result;
}
}
//module.exports = new dbHelper;
exports.get = function(){
console.log("exports.get");
return pool;
}
언급URL : https://stackoverflow.com/questions/54832609/how-to-access-a-function-in-a-function-with-this
반응형
'programing' 카테고리의 다른 글
del, remove 및 pop on 목록의 차이 (0) | 2023.01.24 |
---|---|
Node.js에서 'use strict' 문은 어떻게 해석됩니까? (0) | 2023.01.24 |
MariaDB: 서브쿼리가 실패한 group_concat (0) | 2023.01.24 |
생년월일을 기준으로 나이를 계산하다 (0) | 2023.01.24 |
MySQL InnoDB가 테이블에서 데이터 행을 삭제한 후 디스크 공간을 해제하지 않음 (0) | 2023.01.24 |