송용우

Merge commit 'c0bc6fd4' into feature/rest_api

Showing 53 changed files with 2179 additions and 57 deletions
This diff could not be displayed because it is too large.
......@@ -3,13 +3,25 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.10.2",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"axios": "^0.19.2",
"immer": "^7.0.5",
"include-media": "^1.4.9",
"moment": "^2.27.0",
"open-color": "^1.7.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1"
"react-scripts": "3.4.1",
"redux": "^4.0.5",
"redux-actions": "^2.6.5",
"redux-devtools-extension": "^2.13.8",
"redux-saga": "^1.1.3",
"styled-components": "^5.1.1"
},
"scripts": {
"start": "react-scripts start",
......@@ -31,5 +43,6 @@
"last 1 firefox version",
"last 1 safari version"
]
}
},
"proxy": "http://localhost:4000"
}
......
import React from 'react';
import logo from './logo.svg';
import { Route } from 'react-router-dom';
import './App.css';
import LoginPage from './pages/LoginPage';
import RegisterPage from './pages/RegisterPage';
import HomePage from './pages/HomePage';
import SettingPage from './pages/SettingPage';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
<>
<Route component={HomePage} path={['/@:username', '/']} exact />
<Route component={LoginPage} path="/login" />
<Route component={RegisterPage} path="/register" />
<Route component={SettingPage} path="/setting" />
</>
);
}
......
import React from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import palette from '../../lib/styles/palette';
import Button from '../common/Button';
const AuthFormBlock = styled.div`
h3 {
margin: 0;
color: ${palette.gray[8]};
margin-bottom: 1rem;
}
`;
const StyledInput = styled.input`
font-size: 1rem;
border: none;
border-bottom: 1px solid ${palette.gray[5]};
padding-bottom: 0.5rem;
outline: none;
width: 100%;
&:focus {
color: $oc-teal-7;
border-bottom: 1px solid ${palette.gray[7]};
}
& + & {
margin-top: 1rem;
}
`;
const Footer = styled.div`
margin-top: 2rem;
text-align: right;
a {
color: ${palette.gray[6]};
text-decoration: underline;
&:hover {
color: ${palette.gray[9]};
}
}
`;
const ButtonWithMarginTop = styled(Button)`
margin-top: 1rem;
`;
const ErrorMessage = styled.div`
color: red;
text-align: center;
font-size: 0.875rem;
margin-top: 1rem;
`;
const textMap = {
login: '로그인',
register: '회원가입',
};
const AuthForm = ({ type, form, onChange, onSubmit, error }) => {
const text = textMap[type];
return (
<AuthFormBlock>
<h3>{text}</h3>
<form onSubmit={onSubmit}>
<StyledInput
autoComplete="username"
name="username"
placeholder="아이디"
onChange={onChange}
value={form.username}
/>
<StyledInput
autoComplete="new-password"
name="password"
placeholder="비밀번호"
type="password"
onChange={onChange}
value={form.password}
/>
{type === 'register' && (
<StyledInput
autoComplete="new-password"
name="passwordConfirm"
placeholder="비밀번호 확인"
type="password"
onChange={onChange}
value={form.passwordConfirm}
/>
)}
{error && <ErrorMessage>{error}</ErrorMessage>}
<ButtonWithMarginTop cyan fullWidth>
{text}
</ButtonWithMarginTop>
</form>
<Footer>
{type === 'login' ? (
<Link to="/register">회원가입</Link>
) : (
<Link to="/login">로그인</Link>
)}
</Footer>
</AuthFormBlock>
);
};
export default AuthForm;
import React from 'react';
import styled from 'styled-components';
import palette from '../../lib/styles/palette';
import { Link } from 'react-router-dom';
/*
register/login Layout
*/
const AuthTemplateBlock = styled.div`
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: ${palette.gray[2]};
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`;
const WhiteBox = styled.div`
.logo-area {
display: block;
padding-bottom: 2rem;
text-align: center;
font-weight: bold;
letter-spacing: 2px;
}
box-shadow: 0 0 8px rgba(0, 0, 0, 0.025);
padding: 2rem;
width: 360px;
background: white;
border-radius: 2px;
`;
const AuthTemplate = ({ children }) => {
return (
<AuthTemplateBlock>
<WhiteBox>
<div className="logo-area">
<Link to="/">작심삼일</Link>
</div>
{children}
</WhiteBox>
</AuthTemplateBlock>
);
};
export default AuthTemplate;
import React from 'react';
import styled, { css } from 'styled-components';
import palette from '../../lib/styles/palette';
import { withRouter } from 'react-router-dom';
const StyledButton = styled.button`
border: none;
border-radius: 4px;
font-size: 1rem;
font-weight: bold;
padding: 0.25rem 1rem;
color: white;
outline: none;
cursor: pointer;
background: ${palette.gray[8]};
&:hover {
background: ${palette.gray[6]};
}
${props =>
props.fullWidth &&
css`
padding-top: 0.75rem;
padding-bottom: 0.75rem;
width: 100%;
font-size: 1.125rem;
`}
${props =>
props.cyan &&
css`
background: ${palette.cyan[5]};
&:hover {
background: ${palette.cyan[4]};
}
`}
`;
const Button = ({ to, history, ...rest }) => {
const onClick = e => {
if (to) {
history.push(to);
}
if (rest.onClick) {
rest.onClick(e);
}
};
return <StyledButton {...rest} onClick={onClick} />;
};
export default withRouter(Button);
import React from 'react';
import styled from 'styled-components';
import { NavLink } from 'react-router-dom';
const categories = [
{
name: 'home',
text: '홈',
},
{
name: 'setting',
text: '설정',
},
];
const CategoriesBlock = styled.div`
display: flex;
padding: 1rem;
margin: 0 auto;
@media screen and (max-width: 768px) {
width: 100%;
overflow-x: auto;
}
`;
const Category = styled(NavLink)`
font-size: 1.2rem;
cursor: pointer;
white-space: pre;
text-decoration: none;
color: inherit;
padding-bottom: 0.25rem;
&:hover {
color: #495057;
}
& + & {
margin-left: 2rem;
}
&.active {
font-weight: 600;
border-bottom: 2px solid #22b8cf;
color: #22b8cf;
&:hover {
color: #3bc9db;
}
}
`;
const Categories = () => {
return (
<CategoriesBlock>
{categories.map((c) => (
<Category
activeClassName="active"
key={c.name}
exact={c.name === 'home'}
to={c.name === 'home' ? '/' : `/${c.name}`}
>
{c.text}
</Category>
))}
</CategoriesBlock>
);
};
export default Categories;
import React from 'react';
import styled from 'styled-components';
import Responsive from './Responsive';
import Button from './Button';
import { Link } from 'react-router-dom';
import Categories from './Categories';
const HeaderBlock = styled.div`
position: fixed;
width: 100%;
background: white;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.08);
`;
const Wrapper = styled(Responsive)`
height: 4rem;
display: flex;
align-items: center;
justify-content: space-between;
.logo {
font-size: 1.125rem;
font-weight: 800;
letter-spacing: 2px;
}
.right {
display: flex;
align-items: center;
}
`;
const Spacer = styled.div`
height: 4rem;
`;
const UserInfo = styled.div`
font-weight: 800;
margin-right: 1rem;
`;
const Header = ({ user, onLogout, category, onSelect }) => {
return (
<>
<HeaderBlock>
<Wrapper>
<Link to="/" className="logo">
작심삼일
</Link>
<Categories
category={category}
onSelect={onSelect}
className="right"
/>
{user ? (
<div className="right">
<UserInfo>{user.username}</UserInfo>
<Button onClick={onLogout}>로그아웃</Button>
</div>
) : (
<div className="right">
<Button to="/login">로그인</Button>
</div>
)}
</Wrapper>
</HeaderBlock>
<Spacer />
</>
);
};
export default Header;
import React from 'react';
import styled from 'styled-components';
const ResponsiveBlock = styled.div`
padding-left: 1rem;
padding-right: 1rem;
width: 1024px;
margin: 0 auto;
@media (max-width: 1024px) {
width: 768px;
}
@media (max-width: 768px) {
width: 100%;
}
`;
const Responsive = ({ children, ...rest }) => {
return <ResponsiveBlock {...rest}>{children}</ResponsiveBlock>;
};
export default Responsive;
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import palette from '../../lib/styles/palette';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
background: palette.gray[2],
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
}));
const HomeForm = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={12}>
<Paper className={classes.paper}>xs=12</Paper>
</Grid>
<Grid item xs={6}>
<Paper className={classes.paper}>xs=6</Paper>
</Grid>
<Grid item xs={6}>
<Paper className={classes.paper}>xs=6</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
</Grid>
</div>
);
};
export default HomeForm;
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
margin: theme.spacing(1),
},
},
}));
const BJIDForm = ({ onChange, onBJIDSubmit, profile, onSyncBJIDSubmit }) => {
const classes = useStyles();
return (
<div>
<form onSubmit={onBJIDSubmit}>
<TextField
name="userBJID"
onChange={onChange}
value={profile.userBJID}
placeholder="백준 아이디"
label="백준 아이디"
/>
<Button variant="outlined" type="submit">
등록
</Button>
</form>
<Button variant="outlined" onClick={onSyncBJIDSubmit}>
동기화
</Button>
</div>
);
};
export default BJIDForm;
import React from 'react';
import palette from '../../lib/styles/palette';
import BJIDForm from './BJIDForm';
import SlackForm from './SlackForm';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
background: palette.gray[2],
},
paper: {
margin: 'auto',
textAlign: 'center',
padding: 30,
},
}));
const SettingForm = ({
onChange,
onBJIDSubmit,
onSlackURLSubmit,
profile,
onSyncBJIDSubmit,
}) => {
const classes = useStyles();
return (
<div className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={12}>
<Paper className={classes.paper}>
<h3>{profile.username}</h3>
</Paper>
</Grid>
<Grid container item xs={12}>
<Paper className={classes.paper} elevation={3}>
<BJIDForm
profile={profile}
onChange={onChange}
onBJIDSubmit={onBJIDSubmit}
onSyncBJIDSubmit={onSyncBJIDSubmit}
/>
</Paper>
</Grid>
<Grid container item xs={12}>
<Paper className={classes.paper} elevation={3}>
<SlackForm
profile={profile}
onChange={onChange}
onSlackURLSubmit={onSlackURLSubmit}
/>
</Paper>
</Grid>
</Grid>
</div>
);
};
export default SettingForm;
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
margin: theme.spacing(1),
},
},
}));
const SlackForm = ({ onChange, profile, onSlackURLSubmit }) => {
const classes = useStyles();
return (
<div>
<form onSubmit={onSlackURLSubmit}>
<TextField
name="slackWebHookURL"
onChange={onChange}
value={profile.slackWebHookURL}
placeholder="슬랙 Webhook URL"
label="슬랙 Webhook URL"
/>
<Button variant="outlined" type="submit">
등록
</Button>
</form>
</div>
);
};
export default SlackForm;
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { changeField, initializeForm, login } from '../../modules/auth';
import AuthForm from '../../components/auth/AuthForm';
import { check } from '../../modules/user';
const LoginForm = ({ history }) => {
const dispatch = useDispatch();
const [error, setError] = useState(null);
const { form, auth, authError, user } = useSelector(({ auth, user }) => ({
form: auth.login,
auth: auth.auth,
authError: auth.authError,
user: user.user,
}));
const onChange = (e) => {
const { value, name } = e.target;
dispatch(
changeField({
form: 'login',
key: name,
value,
}),
);
};
const onSubmit = (e) => {
e.preventDefault();
const { username, password } = form;
dispatch(login({ username, password }));
};
useEffect(() => {
dispatch(initializeForm('login'));
}, [dispatch]);
useEffect(() => {
if (authError) {
console.log('Error Occured');
console.log(authError);
setError('로그인 실패');
return;
}
if (auth) {
console.log('Login Success');
dispatch(check());
}
}, [auth, authError, dispatch]);
useEffect(() => {
if (user) {
history.push('/');
try {
localStorage.setItem('user', JSON.stringify(user));
} catch (e) {
console.log('localStorage is not working');
}
console.log(user);
}
}, [history, user]);
return (
<AuthForm
type="login"
form={form}
onChange={onChange}
onSubmit={onSubmit}
error={error}
></AuthForm>
);
};
export default withRouter(LoginForm);
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { changeField, initializeForm, register } from '../../modules/auth';
import AuthForm from '../../components/auth/AuthForm';
import { check } from '../../modules/user';
import { withRouter } from 'react-router-dom';
const RegisterForm = ({ history }) => {
const [error, setError] = useState(null);
const dispatch = useDispatch();
const { form, auth, authError, user } = useSelector(({ auth, user }) => ({
form: auth.register,
auth: auth.auth,
authError: auth.authError,
user: user.user,
}));
const onChange = (e) => {
const { value, name } = e.target;
dispatch(
changeField({
form: 'register',
key: name,
value,
}),
);
};
const onSubmit = (e) => {
e.preventDefault();
const { username, password, passwordConfirm } = form;
if ([username, password, passwordConfirm].includes('')) {
setError('빈 칸을 모두 입력하세요');
return;
}
if (password !== passwordConfirm) {
setError('비밀번호가 일치하지 않습니다.');
changeField({ form: 'register', key: 'password', value: '' });
changeField({ form: 'register', key: 'passwordConfirm', value: '' });
return;
}
dispatch(register({ username, password }));
};
useEffect(() => {
dispatch(initializeForm('register'));
}, [dispatch]);
useEffect(() => {
if (authError) {
if (authError.response.status === 409) {
setError('이미 존재하는 계정명입니다.');
return;
}
setError('회원가입 실패');
return;
}
if (auth) {
console.log('Register Success!');
console.log(auth);
dispatch(check());
}
}, [auth, authError, dispatch]);
useEffect(() => {
if (user) {
console.log('SUCCESS check API');
history.push('/');
try {
localStorage.setItem('user', JSON.stringify(user));
} catch (e) {
console.log('localStorage is not working');
}
}
}, [history, user]);
return (
<AuthForm
type="register"
form={form}
onChange={onChange}
onSubmit={onSubmit}
error={error}
></AuthForm>
);
};
export default withRouter(RegisterForm);
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Header from '../../components/common/Header';
import { logout } from '../../modules/user';
const HeaderContainer = () => {
const { user } = useSelector(({ user }) => ({ user: user.user }));
const dispatch = useDispatch();
const onLogout = () => {
dispatch(logout());
};
return <Header user={user} onLogout={onLogout} />;
};
export default HeaderContainer;
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { withRouter } from 'react-router-dom';
import HomeForm from '../../components/home/HomeForm';
import { getPROFILE } from '../../modules/profile';
import { analyzeBJ } from '../../lib/util/analyzeBJ';
const HomeContainer = ({ history }) => {
const dispatch = useDispatch();
const { user, profile } = useSelector(({ user, profile }) => ({
user: user.user,
profile: profile,
}));
useEffect(() => {}, [profile.solvedBJ]);
useEffect(() => {
if (user) {
let username = user.username;
dispatch(getPROFILE({ username }));
}
}, [dispatch, user]);
return <HomeForm />;
};
export default withRouter(HomeContainer);
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { withRouter } from 'react-router-dom';
import {
changeField,
setBJID,
getPROFILE,
syncBJID,
initializeProfile,
setSLACK,
} from '../../modules/profile';
import SettingForm from '../../components/setting/SettingForm';
const SettingContainer = ({ history }) => {
const dispatch = useDispatch();
const { user, profile } = useSelector(({ user, profile }) => ({
user: user.user,
profile: profile,
}));
const onChange = (e) => {
const { value, name } = e.target;
dispatch(
changeField({
key: name,
value: value,
}),
);
};
const onSyncBJIDSubmit = (e) => {
e.preventDefault();
let username = profile.username;
dispatch(syncBJID({ username }));
};
const onSlackURLSubmit = (e) => {
e.preventDefault();
let username = profile.username;
let slackWebHookURL = profile.slackWebHookURL;
dispatch(setSLACK({ username, slackWebHookURL }));
};
const onBJIDSubmit = (e) => {
e.preventDefault();
let username = profile.username;
let userBJID = profile.userBJID;
dispatch(setBJID({ username, userBJID }));
};
useEffect(() => {
if (!user) {
alert('로그인이 필요합니다 ');
history.push('/');
} else {
let username = user.username;
dispatch(getPROFILE({ username }));
return () => {
dispatch(initializeProfile());
};
}
}, [dispatch, user, history]);
return (
<SettingForm
type="setting"
onChange={onChange}
onBJIDSubmit={onBJIDSubmit}
onSyncBJIDSubmit={onSyncBJIDSubmit}
onSlackURLSubmit={onSlackURLSubmit}
profile={profile}
></SettingForm>
);
};
export default withRouter(SettingContainer);
......@@ -5,6 +5,24 @@ body {
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
box-sizing: border-box;
min-height: 100%;
}
#root {
min-height: 100%;
}
html {
height: 100%;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: inherit;
}
code {
......
......@@ -3,12 +3,41 @@ import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import rootReducer, { rootSaga } from './modules';
import { tempSetUser, check } from './modules/user';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(sagaMiddleware)),
);
function loadUser() {
try {
const user = localStorage.getItem('user');
if (!user) return;
store.dispatch(tempSetUser(user));
store.dispatch(check());
} catch (e) {
console.log('localStorage is not working');
}
}
sagaMiddleware.run(rootSaga);
loadUser();
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
document.getElementById('root'),
);
// If you want your app to work offline and load faster, you can change
......
import client from './client';
export const login = ({ username, password }) =>
client.post('api/auth/login', { username, password });
export const register = ({ username, password }) =>
client.post('api/auth/register', { username, password });
export const check = () => client.get('api/auth/check');
export const logout = () => client.post('/api/auth/logout');
import axios from 'axios';
const client = axios.create();
export default client;
import client from './client';
export const setBJID = ({ username, userBJID }) =>
client.post('api/profile/setprofile', {
username: username,
userBJID: userBJID,
});
export const setPROFILE = (postdata) =>
client.post('api/profile/setprofile', postdata);
export const getPROFILE = ({ username }) =>
client.post('api/profile/getprofile', { username });
export const syncBJ = ({ username }) =>
client.patch('api/profile/syncBJ', { username });
import { call, put } from 'redux-saga/effects';
import { startLoading, finishLoading } from '../modules/loading';
export const createRequestActionTypes = (type) => {
const SUCCESS = `${type}_SUCCESS`;
const FAILURE = `${type}_FAILURE`;
return [type, SUCCESS, FAILURE];
};
export default function createRequestSaga(type, request) {
const SUCCESS = `${type}_SUCCESS`;
const FAILURE = `${type}_FAILURE`;
return function* (action) {
yield put(startLoading(type));
try {
const response = yield call(request, action.payload);
yield put({
type: SUCCESS,
payload: response.data,
});
} catch (e) {
yield put({
type: FAILURE,
payload: e,
error: true,
});
}
yield put(finishLoading(type));
};
}
// source: https://yeun.github.io/open-color/
const palette = {
gray: [
'#f8f9fa',
'#f1f3f5',
'#e9ecef',
'#dee2e6',
'#ced4da',
'#adb5bd',
'#868e96',
'#495057',
'#343a40',
'#212529',
],
cyan: [
'#e3fafc',
'#c5f6fa',
'#99e9f2',
'#66d9e8',
'#3bc9db',
'#22b8cf',
'#15aabf',
'#1098ad',
'#0c8599',
'#0b7285',
],
};
export default palette;
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>
import { createAction, handleActions } from 'redux-actions';
import produce from 'immer';
import { takeLatest } from 'redux-saga/effects';
import createRequestSaga, {
createRequestActionTypes,
} from '../lib/createRequestSaga';
import * as authAPI from '../lib/api/auth';
const CHANGE_FIELD = 'auth/CHANGE_FIELD';
const INITIALIZE_FORM = 'auth/INITIALIZE_FORM';
const [REGISTER, REGISTER_SUCCESS, REGISTER_FAILURE] = createRequestActionTypes(
'auth/REGISTER',
);
const [LOGIN, LOGIN_SUCCESS, LOGIN_FAILURE] = createRequestActionTypes(
'auth/REGISTER',
);
export const changeField = createAction(
CHANGE_FIELD,
({ form, key, value }) => ({
form,
key,
value,
}),
);
export const initializeForm = createAction(INITIALIZE_FORM, (form) => form);
const initalState = {
register: {
username: '',
password: '',
passwordConfirm: '',
},
login: {
username: '',
password: '',
},
auth: null,
authError: null,
};
export const register = createAction(REGISTER, ({ username, password }) => ({
username,
password,
}));
export const login = createAction(LOGIN, ({ username, password }) => ({
username,
password,
}));
const registerSaga = createRequestSaga(REGISTER, authAPI.register);
const loginSaga = createRequestSaga(LOGIN, authAPI.login);
export function* authSaga() {
yield takeLatest(REGISTER, registerSaga);
yield takeLatest(LOGIN, loginSaga);
}
const auth = handleActions(
{
[CHANGE_FIELD]: (state, { payload: { form, key, value } }) =>
produce(state, (draft) => {
draft[form][key] = value;
}),
[INITIALIZE_FORM]: (state, { payload: form }) => ({
...state,
[form]: initalState[form],
authError: null,
}),
[REGISTER_SUCCESS]: (state, { payload: auth }) => ({
...state,
authError: null,
auth,
}),
[REGISTER_FAILURE]: (state, { payload: error }) => ({
...state,
authError: error,
}),
[LOGIN_SUCCESS]: (state, { payload: auth }) => ({
...state,
authError: null,
auth,
}),
[LOGIN_FAILURE]: (state, { payload: error }) => ({
...state,
authError: error,
}),
},
initalState,
);
export default auth;
import { combineReducers } from 'redux';
import { all } from 'redux-saga/effects';
import auth, { authSaga } from './auth';
import loading from './loading';
import user, { userSaga } from './user';
import profile, { profileSaga } from './profile';
const rootReducer = combineReducers({
auth,
loading,
user,
profile,
});
export function* rootSaga() {
yield all([authSaga(), userSaga(), profileSaga()]);
}
export default rootReducer;
import { createAction, handleActions } from 'redux-actions';
const START_LOADING = 'loading/START_LOADING';
const FINISH_LOADING = 'loading/FINISH_LOADING';
export const startLoading = createAction(
START_LOADING,
(requestType) => requestType,
);
export const finishLoading = createAction(
FINISH_LOADING,
(requestType) => requestType,
);
const initialState = {};
const loading = handleActions(
{
[START_LOADING]: (state, action) => ({
...state,
[action.payload]: true,
}),
[FINISH_LOADING]: (state, action) => ({
...state,
[action.payload]: false,
}),
},
initialState,
);
export default loading;
import { createAction, handleActions } from 'redux-actions';
import createRequestSaga, {
createRequestActionTypes,
} from '../lib/createRequestSaga';
import produce from 'immer';
import * as profileAPI from '../lib/api/profile';
import { takeLatest } from 'redux-saga/effects';
const INITIALIZE = 'profile/INITIALIZE';
const CHANGE_FIELD = 'profile/CHANGE_FIELD';
const [SET_BJID, SET_BJID_SUCCESS, SET_BJID_FAILURE] = createRequestActionTypes(
'profile/SET_BJID',
);
const [
SET_SLACK,
SET_SLACK_SUCCESS,
SET_SLACK_FAILURE,
] = createRequestActionTypes('/profile/SET_SLACK');
const [
GET_PROFILE,
GET_PROFILE_SUCCESS,
GET_PROFILE_FAILURE,
] = createRequestActionTypes('profile/GET_PROFILE');
const [
SYNC_BJID,
SYNC_BJID_SUCCESS,
SYNC_BJID_FAILURE,
] = createRequestActionTypes('profile/SYNC_BJID');
export const initializeProfile = createAction(INITIALIZE);
export const syncBJID = createAction(SYNC_BJID, ({ username }) => ({
username,
}));
export const setSLACK = createAction(
SET_SLACK,
({ username, slackWebHookURL }) => ({
username,
slackWebHookURL,
}),
);
export const setBJID = createAction(SET_BJID, ({ username, userBJID }) => ({
username,
userBJID,
}));
export const changeField = createAction(CHANGE_FIELD, ({ key, value }) => ({
key,
value,
}));
export const getPROFILE = createAction(GET_PROFILE, ({ username }) => ({
username,
}));
const initialState = {
username: '',
userBJID: '',
solvedBJ: '',
friendList: [],
profileError: '',
slackWebHookURL: '',
};
const getPROFILESaga = createRequestSaga(GET_PROFILE, profileAPI.getPROFILE);
const setBJIDSaga = createRequestSaga(SET_BJID, profileAPI.setBJID);
const setSLACKSaga = createRequestSaga(SET_SLACK, profileAPI.setPROFILE);
const syncBJIDSaga = createRequestSaga(SYNC_BJID, profileAPI.syncBJ);
export function* profileSaga() {
yield takeLatest(SET_BJID, setBJIDSaga);
yield takeLatest(GET_PROFILE, getPROFILESaga);
yield takeLatest(SYNC_BJID, syncBJIDSaga);
yield takeLatest(SET_SLACK, setSLACKSaga);
}
export default handleActions(
{
[INITIALIZE]: (state) => initialState,
[CHANGE_FIELD]: (state, { payload: { key, value } }) =>
produce(state, (draft) => {
draft[key] = value;
}),
[GET_PROFILE_SUCCESS]: (
state,
{
payload: { username, userBJID, solvedBJ, friendList, slackWebHookURL },
},
) => ({
...state,
username: username,
userBJID: userBJID,
solvedBJ: solvedBJ,
friendList: friendList,
profileError: null,
slackWebHookURL: slackWebHookURL,
}),
[GET_PROFILE_FAILURE]: (state, { payload: error }) => ({
...state,
profileError: error,
}),
[SET_BJID_SUCCESS]: (state, { payload: { userBJID } }) => ({
...state,
userBJID: userBJID,
profileError: null,
}),
[SET_BJID_FAILURE]: (state, { payload: error }) => ({
...state,
profileError: error,
}),
[SET_SLACK_SUCCESS]: (state, { payload: { slackWebHookURL } }) => ({
...state,
slackWebHookURL: slackWebHookURL,
profileError: null,
}),
[SET_SLACK_FAILURE]: (state, { payload: error }) => ({
...state,
profileError: error,
}),
[SYNC_BJID_SUCCESS]: (state, { payload: { solvedBJ } }) => ({
...state,
solvedBJ,
profileError: null,
}),
[SYNC_BJID_FAILURE]: (state, { payload: error }) => ({
...state,
profileError: error,
}),
},
initialState,
);
import { createAction, handleActions } from 'redux-actions';
import { takeLatest, call } from 'redux-saga/effects';
import * as authAPI from '../lib/api/auth';
import createRequestSaga, {
createRequestActionTypes,
} from '../lib/createRequestSaga';
const TEMP_SET_USER = 'user/TEMP_SET_USER';
const [CHECK, CHECK_SUCCESS, CHECK_FAILURE] = createRequestActionTypes(
'user/CHECK',
);
const LOGOUT = 'user/LOGOUT';
export const tempSetUser = createAction(TEMP_SET_USER, (user) => user);
export const check = createAction(CHECK);
export const logout = createAction(LOGOUT);
const checkSaga = createRequestSaga(CHECK, authAPI.check);
function checkFailureSaga() {
try {
localStorage.removeItem('user');
} catch (e) {
console.log('localStroage is not working');
}
}
function* logoutSaga() {
try {
yield call(authAPI.logout);
console.log('logout');
localStorage.removeItem('user');
} catch (e) {
console.log(e);
}
}
export function* userSaga() {
yield takeLatest(CHECK, checkSaga);
yield takeLatest(CHECK_FAILURE, checkFailureSaga);
yield takeLatest(LOGOUT, logoutSaga);
}
const initialState = {
user: null,
checkError: null,
};
export default handleActions(
{
[TEMP_SET_USER]: (state, { payload: user }) => ({
...state,
user,
}),
[CHECK_SUCCESS]: (state, { payload: user }) => ({
...state,
user,
checkError: null,
}),
[CHECK_FAILURE]: (state, { payload: error }) => ({
...state,
user: null,
checkError: error,
}),
[LOGOUT]: (state) => ({
...state,
user: null,
}),
},
initialState,
);
import React from 'react';
import HeaderContainer from '../containers/common/HeaderContainer';
import HomeContainer from '../containers/home/HomeContainer';
const HomePage = () => {
return (
<div>
<HeaderContainer />
<HomeContainer />
</div>
);
};
export default HomePage;
import React from 'react';
import AuthTemplate from '../components/auth/AuthTemplate';
import LoginForm from '../containers/auth/LoginForm';
const LoginPage = () => {
return (
<AuthTemplate>
<LoginForm type="login" />
</AuthTemplate>
);
};
export default LoginPage;
import React from 'react';
import AuthTemplate from '../components/auth/AuthTemplate';
import RegisterForm from '../containers/auth/RegisterForm';
const RegisterPage = () => {
return (
<AuthTemplate>
<RegisterForm type="register" />
</AuthTemplate>
);
};
export default RegisterPage;
import React from 'react';
import HeaderContainer from '../containers/common/HeaderContainer';
import SettingContainer from '../containers/setting/SettingContainer';
const SettingPage = () => {
return (
<div>
<HeaderContainer />
<SettingContainer></SettingContainer>
</div>
);
};
export default SettingPage;
This diff could not be displayed because it is too large.
......@@ -18,20 +18,22 @@
## API Table
| group | description | method | URL | Detail | Auth |
| ------- | --------------------------- | ------ | ------------------------ | -------- | --------- |
| user | 유저 등록 | POST | api/user | 바로가기 | JWT Token |
| user | 유저 삭제 | DELETE | api/user:id | 바로가기 | JWT Token |
| user | 특정 유저 조회 | GET | api/user:id | 바로가기 | None |
| user | 전체 유저 조회 | GET | api/user | 바로가기 | JWT Token |
| friend | 유저 친구 등록 | POST | api/friend | 바로가기 | JWT Token |
| friend | 유저의 친구 조회 | GET | api/friend:id | 바로가기 | None |
| profile | 유저가 푼 문제 조회(백준) | GET | api/profile/solvedBJ:id | 바로가기 | None |
| profile | 유저가 푼 문제 동기화(백준) | PATCH | api/profile/syncBJ | 바로가기 | None |
| profile | 유저 정보 수정 | POST | api/profile/setprofile | 바로가기 | JWT TOKEN |
| profile | 추천 문제 조회 | GET | api/profile/recommend:id | 바로가기 | None |
| notify | 슬랙 메시지 전송 요청 | POST | api/notify/slack | 바로가기 | Jwt Token |
| auth | 로그인 | POST | api/auth/login | 바로가기 | None |
| auth | 로그아웃 | GET | api/auth/logout | 바로가기 | JWT Token |
| auth | 회원가입 | POST | api/auth/register | 바로가기 | None |
| auth | 로그인 확인 | GET | api/auth/check | 바로가기 | None |
| group | description | method | URL | Detail | Auth |
| ------- | --------------------------- | --------- | ------------------------ | -------- | --------- |
| user | 유저 등록 | POST | api/user | 바로가기 | JWT Token |
| user | 유저 삭제 | DELETE | api/user:id | 바로가기 | JWT Token |
| user | 특정 유저 조회 | GET | api/user:id | 바로가기 | None |
| user | 전체 유저 조회 | GET | api/user | 바로가기 | JWT Token |
| friend | 유저 친구 등록 | POST | api/friend | 바로가기 | JWT Token |
| friend | 유저의 친구 조회 | GET | api/friend:id | 바로가기 | None |
| profile | 유저가 푼 문제 조회(백준) | GET | api/profile/solvedBJ:id | 바로가기 | None |
| profile | 유저가 푼 문제 동기화(백준) | PATCH | api/profile/syncBJ | 바로가기 | None |
| profile | 유저 정보 수정 | POST | api/profile/setprofile | 바로가기 | JWT TOKEN |
| profile | 유저 정보 받아오기 | POST | api/profile/getprofile | 바로가기 | JWT |
| profile | 추천 문제 조회 | GET | api/profile/recommend:id | 바로가기 | None |
| notify | 슬랙 메시지 전송 요청 | POST | api/notify/ |
| slack | 바로가기 | Jwt Token |
| auth | 로그인 | POST | api/auth/login | 바로가기 | None |
| auth | 로그아웃 | POST | api/auth/logout | 바로가기 | JWT Token |
| auth | 회원가입 | POST | api/auth/register | 바로가기 | None |
| auth | 로그인 확인 | GET | api/auth/check | 바로가기 | None |
......
This diff could not be displayed because it is too large.
......@@ -5,6 +5,10 @@ const mongoose = require("mongoose");
const fs = require("fs");
const morgan = require("koa-morgan");
const jwtMiddleware = require("./src/lib/jwtMiddleware");
const api = require("./src/api");
require("dotenv").config();
const app = new Koa();
const router = new Router();
const accessLogStream = fs.createWriteStream(__dirname + "/access.log", {
......@@ -14,7 +18,6 @@ require("dotenv").config();
app.use(bodyParser());
app.use(jwtMiddleware);
app.use(morgan("combined", { stream: accessLogStream }));
const api = require("./src/api");
const { SERVER_PORT, MONGO_URL } = process.env;
router.use("/api", api.routes());
......@@ -32,6 +35,7 @@ mongoose
.catch((e) => {
console.log(e);
});
app.listen(SERVER_PORT, () => {
console.log("Server is running on port", process.env.SERVER_PORT);
});
......
This diff is collapsed. Click to expand it.
......@@ -21,7 +21,10 @@
"koa-router": "^9.0.1",
"mongoose": "^5.9.17",
"morgan": "^1.10.0",
"node-schedule": "^1.3.2",
"path": "^0.12.7",
"slack-client": "^2.0.6",
"slack-node": "^0.1.8",
"voca": "^1.4.0"
},
"devDependencies": {
......
......@@ -40,7 +40,7 @@ exports.register = async (ctx) => {
ctx.body = user.serialize();
const token = user.generateToken();
ctx.cookies.set("acces_token", token, {
ctx.cookies.set("access_token", token, {
//3일동안 유효
maxAge: 1000 * 60 * 60 * 24 * 3,
httpOnly: true,
......@@ -75,7 +75,7 @@ exports.login = async (ctx) => {
}
ctx.body = user.serialize();
const token = user.generateToken();
ctx.cookies.set("acces_token", token, {
ctx.cookies.set("access_token", token, {
//7일동안 유효
maxAge: 1000 * 60 * 60 * 24 * 7,
httpOnly: true,
......
......@@ -2,7 +2,8 @@ const Router = require("koa-router");
const auth = new Router();
const authCtrl = require("./auth.ctrl");
auth.post("/login", authCtrl.login);
auth.get("/logout", authCtrl.logout);
auth.post("/logout", authCtrl.logout);
auth.post("/register", authCtrl.register);
auth.get("/check", authCtrl.check);
module.exports = auth;
......
......@@ -7,4 +7,5 @@ profile.get("/solvednum:id");
profile.get("/recommendps:id");
profile.patch("/syncBJ", profileCtrl.syncBJ);
profile.post("/setprofile", profileCtrl.setProfile);
profile.post("/getprofile", profileCtrl.getProfile);
module.exports = profile;
......
......@@ -13,6 +13,24 @@ exports.checkObjectId = (ctx, next) => {
}
return next();
};
/*POST /api/profile/getprofile
{
username: "username"
}
*/
exports.getProfile = async (ctx) => {
try {
const { username } = ctx.request.body;
const profile = await Profile.findByUsername(username);
if (!profile) {
ctx.status = 401;
return;
}
ctx.body = profile;
} catch (e) {
ctx.throw(500, e);
}
};
/*
POST /api/proflie/setprofile
{
......
export const problem_set = [
"1517",
"2448",
"1891",
"1074",
"2263",
"1780",
"11728",
"10816",
"10815",
"2109",
"1202",
"1285",
"2138",
"1080",
"11399",
"1931",
"11047",
"15666",
"15665",
"15664",
"15663",
"15657",
"15656",
"15655",
"15654",
"15652",
"15651",
"15650",
"15649",
"6603",
"10971",
"10819",
"10973",
"10974",
"10972",
"7576",
"1248",
"2529",
"15661",
"14501",
"1759",
"14391",
"14889",
"1182",
"11723",
"1748",
"6064",
"1107",
"3085",
"2309",
"1748",
"14500",
"1107",
"1476",
"3085",
"2309",
"1261",
"13549",
"14226",
"13913",
"1697",
"1967",
"1167",
"11725",
"2250",
"1991",
"7562",
"2178",
"4963",
"2667",
"1707",
"11724",
"1260",
"13023",
"11652",
"1377",
"11004",
"10825",
"2751",
"9461",
"1699",
"9095",
"2225",
"2133",
"11727",
"11726",
"1463",
"2748",
"2747",
"11656",
"10824",
"2743",
"10820",
"10808",
"11655",
"11720",
"1008",
"10951",
"2557",
"1021",
"1966",
"2164",
"10799",
"17413",
"10866",
"1158",
"10845",
"1406",
"1874",
"9012",
"9093",
"10828",
"11721",
"11719",
"11718",
"10953",
"2558",
"10814",
"1181",
"11651",
"11650",
"1427",
"2108",
"10989",
"2751",
"2750",
"1436",
"1018",
"7568",
"2231",
"2798",
"1002",
"3053",
"4153",
"3009",
"1085",
"9020",
"4948",
"1929",
"2581",
"1978",
"2292",
"6064",
"2775",
"10250",
"2869",
"1011",
"1193",
"2839",
"1712",
"1316",
"2941",
"5622",
"2908",
"1152",
"1157",
"2675",
"10809",
"11720",
"11654",
"11729",
"2447",
"3052",
"10818",
"10872",
"10870",
"1065",
"4673",
"15596",
"4344",
"2920",
"8958",
"1546",
"2577",
"2562",
"1110",
"10951",
"10952",
"10871",
"2439",
"2438",
"11022",
"11021",
"2742",
"2741",
"15552",
"8393",
"10950",
"2739",
"10817",
"2884",
"2753",
"9498",
"1330",
"2588",
"10430",
"10869",
"1008",
"10998",
"7287",
"10172",
"10171",
"10718",
"1001",
"1000",
"2557",
];
const jwt = require("jsonwebtoken");
const User = require("../models/user");
const jwtMiddleware = async (ctx, next) => {
const token = ctx.cookies.get("access_token");
if (!token) {
//토큰이 없을 때
return next();
}
try {
const decoded = jwt.verify(token, process.env.JWT_TOKEN);
const decoded = jwt.verify(token, process.env.JWT_SECRET);
ctx.state.user = {
_id: decoded._id,
username: decoded.username,
};
//토큰의 남은 유효 기간이 2일 이하라면 재발급
if (decoded.exp - Date.now() / 1000 < 60 * 60 * 24 * 2) {
const now = Math.floor(Date.now() / 1000);
if (decoded.exp - now < 60 * 60 * 24 * 3.5) {
const user = await User.findById(decoded._id);
const token = user.generateToken();
ctx.cookies.set("access_token", token, {
maxAge: 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7, //7days
httpOnly: true,
});
}
return next();
} catch (e) {
return next();
}
};
module.exports = jwtMiddleware;
......
......@@ -7,6 +7,7 @@ const ProfileSchema = new Schema({
userBJID: String,
solvedBJ: Object,
friendList: [String],
slackWebHookURL: String,
});
ProfileSchema.statics.findByUsername = function (username) {
return this.findOne({ username });
......
/*
2. 현재 날짜와의 차이 =>
3. 오늘 푼 문제 => 앞에서부터 순회하면서 데이트 같은거 찾기
3. 최근 일주일간 푼 문제 수 => 앞에서부터 순회하면서 - 값이
4. 추천 문제 => 정규 셋에서 없는거 찾기
5. 날짜별로 묶기.
데이터베이스에서 처리하자
*/
let moment = require('moment');
exports.analyzeBJ = function (solvedBJ) {
try {
if (solvedBJ) {
console.log(solvedBJ[0]);
let presentDate = moment();
let presentDate_str = presentDate.format('YYYYMMDD');
let latestDate = moment(solvedBJ[0].solved_date, 'YYYYMMDD');
let difflatest = presentDate.diff(latestDate, 'days');
let solvedBJbyDATE = {};
for (let i = 0; i < solvedBJ.length; i++) {
if (!(solvedBJ[i].solved_date in solvedBJbyDATE)) {
solvedBJbyDATE[solvedBJ[i].solved_date] = [];
solvedBJbyDATE[solvedBJ[i].solved_date].push(solvedBJ[i]);
} else {
solvedBJbyDATE[solvedBJ[i].solved_date].push(solvedBJ[i]);
}
}
let latestNum = solvedBJbyDATE[solvedBJ[0].solved_date].length;
let presentNum =
presentDate_str in solvedBJbyDATE
? solvedBJbyDATE[presentDate_str].length
: 0;
let returnOBJ = {
latestDate: latestDate.format('YYYYMMDD'),
difflatest: difflatest,
latestNum: latestNum,
presentNum: presentNum,
solvedBJbyDATE: solvedBJbyDATE,
};
console.log(returnOBJ);
return returnOBJ;
}
} catch (e) {
console.log(e);
}
};
/*
집중을 해보자.
새거와 데이터가 있다.
데이터 기준으로 새거에 자료가 있으면 넘어가기
없으면 새 배열에 추가
키만 모아둔 리스트를 만들자.
그렇게 해서
반복은 새거 길이만큼
데이터에 있으면 추가 X
없으면 추가
그렇게 반환
*/
exports.compareBJ = function (solvedBJ_new, problem_set) {
try {
let new_obj = [];
for (let i = 0; i < solvedBJ.length; i++) {
if (solvedBJ_new[i].problem_number in problem_set) {
new_obj.push(solvedBJ_new[i]);
}
}
console.log(new_obj);
} catch (e) {
console.log(e);
}
};
const Slack = require("slack-node"); // 슬랙 모듈 사용
const webhookUri =
"https://hooks.slack.com/services/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"; // Webhook URL
const slack = new Slack();
slack.setWebhook(webhookUri);
const send = async (message) => {
slack.webhook(
{
text: message,
},
function (err, response) {
console.log(response);
}
);
};
send("hello");
var getBJ = require("./getBJ");
var fs = require("fs");
let dataset = [
"1517",
"2448",
"1891",
"1074",
"2263",
"1780",
"11728",
"10816",
"10815",
"2109",
"1202",
"1285",
"2138",
"1080",
"11399",
"1931",
"11047",
"15666",
"15665",
"15664",
"15663",
"15657",
"15656",
"15655",
"15654",
"15652",
"15651",
"15650",
"15649",
"6603",
"10971",
"10819",
"10973",
"10974",
"10972",
"7576",
"1248",
"2529",
"15661",
"14501",
"1759",
"14391",
"14889",
"1182",
"11723",
"1748",
"6064",
"1107",
"3085",
"2309",
"1748",
"14500",
"1107",
"1476",
"3085",
"2309",
"1261",
"13549",
"14226",
"13913",
"1697",
"1967",
"1167",
"11725",
"2250",
"1991",
"7562",
"2178",
"4963",
"2667",
"1707",
"11724",
"1260",
"13023",
"11652",
"1377",
"11004",
"10825",
"2751",
"9461",
"1699",
"9095",
"2225",
"2133",
"11727",
"11726",
"1463",
"2748",
"2747",
"11656",
"10824",
"2743",
"10820",
"10808",
"11655",
"11720",
"1008",
"10951",
"2557",
"1021",
"1966",
"2164",
"10799",
"17413",
"10866",
"1158",
"10845",
"1406",
"1874",
"9012",
"9093",
"10828",
"11721",
"11719",
"11718",
"10953",
"2558",
"10814",
"1181",
"11651",
"11650",
"1427",
"2108",
"10989",
"2751",
"2750",
"1436",
"1018",
"7568",
"2231",
"2798",
"1002",
"3053",
"4153",
"3009",
"1085",
"9020",
"4948",
"1929",
"2581",
"1978",
"2292",
"6064",
"2775",
"10250",
"2869",
"1011",
"1193",
"2839",
"1712",
"1316",
"2941",
"5622",
"2908",
"1152",
"1157",
"2675",
"10809",
"11720",
"11654",
"11729",
"2447",
"3052",
"10818",
"10872",
"10870",
"1065",
"4673",
"15596",
"4344",
"2920",
"8958",
"1546",
"2577",
"2562",
"1110",
"10951",
"10952",
"10871",
"2439",
"2438",
"11022",
"11021",
"2742",
"2741",
"15552",
"8393",
"10950",
"2739",
"10817",
"2884",
"2753",
"9498",
"1330",
"2588",
"10430",
"10869",
"1008",
"10998",
"7287",
"10172",
"10171",
"10718",
"1001",
"1000",
"2557",
];
const test = async (userid) => {
let lst = await getBJ.getBJ(userid);
let return_lst = [];
for (let i = 0; i < lst.length; i++) {
return_lst.push(lst[i].problem_number);
}
var stringJson = JSON.stringify(return_lst) + "\n";
fs.open("test.json", "a", "666", function (err, id) {
if (err) {
console.log("file open err!!");
} else {
fs.write(id, stringJson, null, "utf8", function (err) {
console.log("file was saved!");
});
}
});
};
/*
*/
test("jwseo001");
[
"1517",
"2448",
"1891",
"1074",
"2263",
"1780",
"11728",
"10816",
"10815",
"2109",
"1202",
"1285",
"2138",
"1080",
"11399",
"1931",
"11047",
"15666",
"15665",
"15664",
"15663",
"15657",
"15656",
"15655",
"15654",
"15652",
"15651",
"15650",
"15649",
"6603",
"10971",
"10819",
"10973",
"10974",
"10972",
"7576",
"1248",
"2529",
"15661",
"14501",
"1759",
"14391",
"14889",
"1182",
"11723",
"1748",
"6064",
"1107",
"3085",
"2309",
"1748",
"14500",
"1107",
"1476",
"3085",
"2309",
"1261",
"13549",
"14226",
"13913",
"1697",
"1967",
"1167",
"11725",
"2250",
"1991",
"7562",
"2178",
"4963",
"2667",
"1707",
"11724",
"1260",
"13023",
"11652",
"1377",
"11004",
"10825",
"2751",
"9461",
"1699",
"9095",
"2225",
"2133",
"11727",
"11726",
"1463",
"2748",
"2747",
"11656",
"10824",
"2743",
"10820",
"10808",
"11655",
"11720",
"1008",
"10951",
"2557",
"1021",
"1966",
"2164",
"10799",
"17413",
"10866",
"1158",
"10845",
"1406",
"1874",
"9012",
"9093",
"10828",
"11721",
"11719",
"11718",
"10953",
"2558",
"10814",
"1181",
"11651",
"11650",
"1427",
"2108",
"10989",
"2751",
"2750",
"1436",
"1018",
"7568",
"2231",
"2798",
"1002",
"3053",
"4153",
"3009",
"1085",
"9020",
"4948",
"1929",
"2581",
"1978",
"2292",
"6064",
"2775",
"10250",
"2869",
"1011",
"1193",
"2839",
"1712",
"1316",
"2941",
"5622",
"2908",
"1152",
"1157",
"2675",
"10809",
"11720",
"11654",
"11729",
"2447",
"3052",
"10818",
"10872",
"10870",
"1065",
"4673",
"15596",
"4344",
"2920",
"8958",
"1546",
"2577",
"2562",
"1110",
"10951",
"10952",
"10871",
"2439",
"2438",
"11022",
"11021",
"2742",
"2741",
"15552",
"8393",
"10950",
"2739",
"10817",
"2884",
"2753",
"9498",
"1330",
"2588",
"10430",
"10869",
"1008",
"10998",
"7287",
"10172",
"10171",
"10718",
"1001",
"1000",
"2557"
]