Skip to content

Instantly share code, notes, and snippets.

@LuoZijun
Created July 25, 2018 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LuoZijun/c76296f699e34adcc0cb9bc1e10af752 to your computer and use it in GitHub Desktop.
Save LuoZijun/c76296f699e34adcc0cb9bc1e10af752 to your computer and use it in GitHub Desktop.
import React from 'react'
import ReactDOM from 'react-dom'
import ApolloClient from "apollo-boost";
import gql from "graphql-tag";
import * as Antd from 'antd-mobile'
import * as ReactApollo from 'react-apollo';
const API_URI = "https://beta-ark.ecflag.net/graphql";
const APOLLO_CLIENT = new ApolloClient({
uri: API_URI,
request: async function (operation){
let token = window.localStorage.getItem('token');
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : "",
}
});
}
});
const AUTH_STMT = gql`mutation {
testLogin(email: "hi@example.com", password: "impasswd") {
access_token
}
}`;
class Auth extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render (){
let self = this;
return (
<ReactApollo.Mutation
mutation={AUTH_STMT}
variables={{}}
notifyOnNetworkStatusChange
onCompleted={function (result){
window.localStorage.setItem("token", result.testLogin.access_token);
}}
onError={function (e){
console.error(e);
Antd.Toast.info('身份认证出现了一些问题 ...', 1);
}}>
{function (mutate, result){
if ( result.called === false ) {
mutate();
return null;
} else {
if ( result.data !== undefined ) {
return self.props.children;
} else if ( result.loading ) {
return <p>loading ...</p>;
} else if ( result.error ) {
return <p>登录出现了一些问题 ...</p>;
} else {
throw new Error("unreachable");
}
}
}}
</ReactApollo.Mutation>
);
}
}
Auth.propTypes = {};
Auth.defaultProps = {};
class Page extends React.Component {
render (){
let self = this;
return (
<Auth ref="auth" required={false}>
<h1>It Works!</h1>
</Auth>
);
}
}
function main(){
let vdom = (
<ReactApollo.ApolloProvider client={APOLLO_CLIENT}>
<BrowserRouter>
<div>
<Route exact path="/" component={Page} />
</div>
</BrowserRouter>
</ReactApollo.ApolloProvider>
);
ReactDOM.render(vdom, document.getElementById('root'));
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment