Skip to content

Instantly share code, notes, and snippets.

@uyu423
Created September 18, 2017 08:28
Show Gist options
  • Save uyu423/9e29f5e62d33e54935bf74a3e39d6c9d to your computer and use it in GitHub Desktop.
Save uyu423/9e29f5e62d33e54935bf74a3e39d6c9d to your computer and use it in GitHub Desktop.
const knex = require('knex')({
client: 'mysql',
connection: {
host: 'hostname',
user: 'usernmae',
password: 'password',
database: 'dbname',
},
});
const fetch = require('node-fetch');
const async = require('async');
async function main() {
const targetUserIds = await getUserIdsByPurchasedTrue();
console.log(`target user ids ${targetUserIds.length}`);
await upsertCahnnelIO(targetUserIds);
}
async function getUserIdsByPurchasedTrue() {
const users = await knex.raw('select idx from user where purchased != 0');
return users[0].map(user => user.idx);
}
async function upsertCahnnelIO(userIds) {
async.eachSeries(userIds, (userId, callback) => {
// console.log(`try ${userId}`);
getUserByPlatingAPI(userId).then((user) => {
console.log(`get success userData ${userId}`);
return user;
}).then((user) => {
requestUpsertToChannel(user).then((result) => {
console.log(`${user.idx} ${result}`);
callback();
});
});
}, () => {
console.log('done');
});
}
async function getUserByPlatingAPI(userId) {
const response = await fetch(`https://apiserver.com/user/${userId}?includePurchaseInfo=true`, {
headers: {
'Access-Token': 'tOkEn',
'content-type': 'application/json',
},
});
const user = await response.json();
return user;
}
async function requestUpsertToChannel(user) {
console.log(`try ${user.idx} channel POST req`);
const body = JSON.stringify(reformatUserData(user));
// console.log(body);
const response = await fetch('https://api.channel.io/open/users', {
method: 'POST',
headers: {
'X-Access-Key': 'accessKey',
'X-Access-Secret': 'SecretKey',
'content-type': 'application/json',
Accept: 'application/json',
},
body,
});
if (response.status !== 200) {
const result = await response.json();
console.log(result, body);
}
return response.status === 200 || false;
}
function reformatUserData(userData) {
const data = {};
data[userData.idx] = {
name: userData.name,
mobileNumber: userData.mobile || undefined,
meta: {
'유저 번호': userData.idx,
'유저 코드': userData.userCode,
'보유 포인트': userData.point,
'구매 횟수': userData.purchaseCount,
'총 실결제 금액': userData.sumTotalPrice,
'로그인 타입': userData.loginType,
이메일: userData.email,
'운영체제 타입': userData.osType,
'운영체제 버전': userData.osVersion,
생일: userData.birthday || undefined,
'만 나이': userData.age || undefined,
'계정 생성일': userData.createdAt,
'추천인 유저 번호': userData.refUserIdx,
},
};
// console.log(data);
return data;
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment