Fakultas Ilmu Komputer UI

Commit b3f14087 authored by Zamil Majdy's avatar Zamil Majdy
Browse files

Implement JS fetch for upload from library

parent 3345a9cb
...@@ -14,30 +14,30 @@ export default class VacancyPage extends React.Component { ...@@ -14,30 +14,30 @@ export default class VacancyPage extends React.Component {
password: '', password: '',
errorFlag: false, errorFlag: false,
vacancies: [], vacancies: [],
student: false,
}; };
Storage.getUserData().then(r => this.setState({ student: r.student }));
this.handleItemClick = this.handleItemClick.bind(this); this.handleItemClick = this.handleItemClick.bind(this);
} }
handleItemClick = (e, { name }) => this.setState({ activeItem: name }); handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() { render = () => (
const student = Storage.get('user-data').student; this.state.student && (
return (
<div className="halamanLowongan"> <div className="halamanLowongan">
<Tabs selected={0}> <Tabs selected={0}>
<Pane label="Semua Lowongan" > <Pane label="Semua Lowongan" >
<VacancyList key={1} studentId={student.id} url="/vacancies/" /> <VacancyList key={1} studentId={this.state.student.id} url="/vacancies/" />
</Pane> </Pane>
<Pane label="Lamaran saya" > <Pane label="Lamaran saya" >
<VacancyList key={2} status="Batal" studentId={student.id} url={`/students/${student.id}/applied-vacancies/`} /> <VacancyList key={2} status="Batal" studentId={this.state.student.id} url={`/students/${this.state.student.id}/applied-vacancies/`} />
</Pane> </Pane>
<Pane label="Lamaran Ditandai" > <Pane label="Lamaran Ditandai" >
<VacancyList key={3} studentId={student.id} url={`/students/${student.id}/bookmarked-vacancies/`} /> <VacancyList key={3} studentId={this.state.student.id} url={`/students/${this.state.student.id}/bookmarked-vacancies/`} />
</Pane> </Pane>
</Tabs> </Tabs>
</div> </div>
)
); );
}
} }
...@@ -32,23 +32,8 @@ export default class RegisterModal extends React.Component { ...@@ -32,23 +32,8 @@ export default class RegisterModal extends React.Component {
handleSubmit = (e) => { handleSubmit = (e) => {
e.preventDefault(); e.preventDefault();
const form = new FormData();
Object.keys(this.state).map(k => form.append(k, this.state[k]));
const data = { Server.submit('/register/', this.state).then((response) => {
'X-CSRFToken': Server.getCookie('csrftoken'),
mode: 'no-cors',
method: 'POST',
body: form,
credentials: 'same-origin',
};
fetch('/api/register/', data)
.then((response) => {
if (response.status < 200 || response.status > 399) throw response.json();
else return response.json();
})
.then((response) => {
alert('Akun berhasil dibuat :)'); alert('Akun berhasil dibuat :)');
Storage.set('user-data', response); Storage.set('user-data', response);
browserHistory.push('/home'); browserHistory.push('/home');
......
...@@ -28,9 +28,12 @@ export default class App extends React.Component { ...@@ -28,9 +28,12 @@ export default class App extends React.Component {
Server.isLoggedIn() || replace({ pathname: '/login' }) Server.isLoggedIn() || replace({ pathname: '/login' })
); );
handleHome= (nextState, replace) => { handleHome= (nextState, replace, cb) => {
if (Server.isLoggedIn()) { if (Server.isLoggedIn()) {
Storage.get('user-data').student ? replace({pathname: '/lowongan'}) : replace({pathname: '/profile'}); Storage.getUserData().then((data) => {
const next = data.student ? '/lowongan' : '/profile';
replace({ pathname: next }); cb();
});
} else { } else {
replace({ pathname: '/login' }); replace({ pathname: '/login' });
} }
...@@ -40,7 +43,6 @@ export default class App extends React.Component { ...@@ -40,7 +43,6 @@ export default class App extends React.Component {
<Router history={browserHistory}> <Router history={browserHistory}>
<Route path="/login" component={Login} /> <Route path="/login" component={Login} />
<Route component={Dashboard} onEnter={this.handleAuth}> <Route component={Dashboard} onEnter={this.handleAuth}>
<Route path="/" component={VacancyPage} />
<Route path="/profile" component={Profile} /> <Route path="/profile" component={Profile} />
<Route path="/lowongan" component={VacancyPage} /> <Route path="/lowongan" component={VacancyPage} />
<Route path="/users" component={Profile} /> <Route path="/users" component={Profile} />
......
...@@ -17,8 +17,23 @@ export default class Server { ...@@ -17,8 +17,23 @@ export default class Server {
return null; return null;
} }
static submit(path, data, method = 'POST', useCache = false) {
const form = new FormData();
/* istanbul ignore next */
Object.keys(data).map(k => form.append(k, this.state[k]));
const requestData = {
'X-CSRFToken': Server.getCookie('csrftoken'),
mode: 'no-cors',
method: 'POST',
body: form,
credentials: 'same-origin',
};
return this.handleFetchRequest(requestData, path, useCache);
}
static sendRequest(path, method, data, useCache = false) { static sendRequest(path, method, data, useCache = false) {
const url = `/api${path}`;
const csrftoken = this.getCookie('csrftoken'); const csrftoken = this.getCookie('csrftoken');
const headers = { const headers = {
'content-type': 'application/json', 'content-type': 'application/json',
...@@ -32,7 +47,11 @@ export default class Server { ...@@ -32,7 +47,11 @@ export default class Server {
credentials: 'same-origin', credentials: 'same-origin',
}; };
// noinspection JSUnresolvedFunction return this.handleFetchRequest(requestData, path, useCache);
}
static handleFetchRequest(requestData, path, useCache) {
const url = `/api${path}`;
const request = fetch(url, requestData); const request = fetch(url, requestData);
/* istanbul ignore next */ /* istanbul ignore next */
...@@ -43,12 +62,8 @@ export default class Server { ...@@ -43,12 +62,8 @@ export default class Server {
const contentType = response.headers.get('content-type'); const contentType = response.headers.get('content-type');
const result = contentType && contentType.indexOf('application/json') !== -1 ? response.json() : response.text(); const result = contentType && contentType.indexOf('application/json') !== -1 ? response.json() : response.text();
if (response.status < 200 || response.status > 399) { if (response.status < 200 || response.status > 399) throw result;
throw result; else return result;
}
else {
return result;
}
}); });
/* istanbul ignore next */ /* istanbul ignore next */
......
import Server from './../lib/Server';
/** Session Storage Polyfill */ /** Session Storage Polyfill */
/* eslint-disable */ /* eslint-disable */
...@@ -120,14 +122,23 @@ polyfil(); ...@@ -120,14 +122,23 @@ polyfil();
export default class Storage { export default class Storage {
static get(key) { static get(key) {
return JSON.parse(sessionStorage.getItem(key)); return JSON.parse(localStorage.getItem(key));
} }
static set(key, value) { static set(key, value) {
return sessionStorage.setItem(key, JSON.stringify(value)); return localStorage.setItem(key, JSON.stringify(value));
} }
static clear() { static clear() {
return sessionStorage.clear(); return localStorage.clear();
}
static getUserData() {
const data = Storage.get('user-data');
/* istanbul ignore next */
return (data != null) ? Promise.resolve(data) : Server.get('/users/me/').then((response) => {
Storage.set(('user-data'), response);
return response;
});
} }
} }
...@@ -4,14 +4,14 @@ from rest_framework import serializers ...@@ -4,14 +4,14 @@ from rest_framework import serializers
from core.models.accounts import Supervisor, Company, Student from core.models.accounts import Supervisor, Company, Student
class UserSerializer(serializers.HyperlinkedModelSerializer): class BasicUserSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = User model = User
fields = ('url', 'username', 'email', 'is_staff') fields = ('url', 'username', 'email', 'is_staff')
class StudentSerializer(serializers.ModelSerializer): class StudentSerializer(serializers.ModelSerializer):
user = UserSerializer() user = BasicUserSerializer()
name = serializers.ReadOnlyField() name = serializers.ReadOnlyField()
class Meta: class Meta:
...@@ -20,7 +20,7 @@ class StudentSerializer(serializers.ModelSerializer): ...@@ -20,7 +20,7 @@ class StudentSerializer(serializers.ModelSerializer):
class CompanySerializer(serializers.ModelSerializer): class CompanySerializer(serializers.ModelSerializer):
user = UserSerializer() user = BasicUserSerializer()
name = serializers.ReadOnlyField() name = serializers.ReadOnlyField()
class Meta: class Meta:
...@@ -29,7 +29,7 @@ class CompanySerializer(serializers.ModelSerializer): ...@@ -29,7 +29,7 @@ class CompanySerializer(serializers.ModelSerializer):
class SupervisorSerializer(serializers.ModelSerializer): class SupervisorSerializer(serializers.ModelSerializer):
user = UserSerializer() user = BasicUserSerializer()
name = serializers.ReadOnlyField() name = serializers.ReadOnlyField()
class Meta: class Meta:
...@@ -37,7 +37,7 @@ class SupervisorSerializer(serializers.ModelSerializer): ...@@ -37,7 +37,7 @@ class SupervisorSerializer(serializers.ModelSerializer):
fields = '__all__' fields = '__all__'
class LoginSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.HyperlinkedModelSerializer):
company = CompanySerializer() company = CompanySerializer()
supervisor = SupervisorSerializer() supervisor = SupervisorSerializer()
student = StudentSerializer() student = StudentSerializer()
......
...@@ -11,8 +11,8 @@ from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_409_CONFLICT ...@@ -11,8 +11,8 @@ from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_409_CONFLICT
from core.lib.permissions import IsAdminOrStudent, IsAdminOrSelfOrReadOnly, IsAdminOrCompany, IsAdminOrSupervisor from core.lib.permissions import IsAdminOrStudent, IsAdminOrSelfOrReadOnly, IsAdminOrCompany, IsAdminOrSupervisor
from core.models.accounts import Student, Company, Supervisor from core.models.accounts import Student, Company, Supervisor
from core.serializers.accounts import UserSerializer, StudentSerializer, CompanySerializer, SupervisorSerializer, \ from core.serializers.accounts import BasicUserSerializer, StudentSerializer, CompanySerializer, SupervisorSerializer, \
LoginSerializer, RegisterSerializer UserSerializer, RegisterSerializer
class UserViewSet(viewsets.ModelViewSet): class UserViewSet(viewsets.ModelViewSet):
...@@ -26,7 +26,7 @@ class UserViewSet(viewsets.ModelViewSet): ...@@ -26,7 +26,7 @@ class UserViewSet(viewsets.ModelViewSet):
Get current user's details Get current user's details
""" """
user = self.request.user user = self.request.user
serializer = UserSerializer(user, context={"request": request}) serializer = BasicUserSerializer(user, context={"request": request})
return Response(serializer.data) return Response(serializer.data)
def get_permissions(self): def get_permissions(self):
...@@ -62,7 +62,7 @@ class SupervisorViewSet(viewsets.ModelViewSet): ...@@ -62,7 +62,7 @@ class SupervisorViewSet(viewsets.ModelViewSet):
class LoginViewSet(viewsets.GenericViewSet): class LoginViewSet(viewsets.GenericViewSet):
permission_classes = (AllowAny, ) permission_classes = (AllowAny, )
serializer_class = LoginSerializer serializer_class = UserSerializer
queryset = User.objects.all() queryset = User.objects.all()
def create(self, request): def create(self, request):
...@@ -115,9 +115,9 @@ class LoginViewSet(viewsets.GenericViewSet): ...@@ -115,9 +115,9 @@ class LoginViewSet(viewsets.GenericViewSet):
nip=resp.get("kodeidentitas") nip=resp.get("kodeidentitas")
) )
supervisor.save() supervisor.save()
serializer = LoginSerializer(user, context={'request': request}) serializer = UserSerializer(user, context={'request': request})
return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_201_CREATED)
serializer = LoginSerializer(user, context={'request': request}) serializer = UserSerializer(user, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_200_OK)
else: else:
return Response(status=status.HTTP_401_UNAUTHORIZED) return Response(status=status.HTTP_401_UNAUTHORIZED)
...@@ -125,7 +125,7 @@ class LoginViewSet(viewsets.GenericViewSet): ...@@ -125,7 +125,7 @@ class LoginViewSet(viewsets.GenericViewSet):
user = authenticate(username = username, password = password) user = authenticate(username = username, password = password)
if user is not None: if user is not None:
login(request, user) login(request, user)
serializer = LoginSerializer(user, context={'request': request}) serializer = UserSerializer(user, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_200_OK)
else: else:
return Response(status=status.HTTP_401_UNAUTHORIZED) return Response(status=status.HTTP_401_UNAUTHORIZED)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment