Skip to content

Commit f2b0f64

Browse files
committed
Refactoring code
1 parent 061cf96 commit f2b0f64

File tree

8 files changed

+89
-57
lines changed

8 files changed

+89
-57
lines changed

client/components/AppFrame.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ const decorate = withStyles((theme) => ({
77
'@global': {
88
html: {
99
background: theme.palette.background.default,
10-
WebkitFontSmoothing: 'antialiased', // Antialiasing.
11-
MozOsxFontSmoothing: 'grayscale', // Antialiasing.
10+
WebkitFontSmoothing: 'antialiased', // Antialiasing
11+
MozOsxFontSmoothing: 'grayscale', // Antialiasing
1212
},
1313
body: {
1414
margin: 0,

client/contexts/ThemeContext.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from 'react';
22
import {PaletteType} from '@material-ui/core';
33

44
const getPaletteType = (): PaletteType => {
5-
const defaultTheme: PaletteType = 'dark';
5+
const defaultTheme: PaletteType = 'light';
66
try {
77
const find = localStorage.getItem('paletteType');
88
if (find === null) {

client/with/initApollo.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ if (!process.browser) {
1313
global.fetch = fetch;
1414
}
1515

16-
const create = (initialState: any, {getToken}: any, req?: any) => {
16+
const create = (initialState: any, {getToken}: {getToken: () => string}, req?: any) => {
1717
const baseUrl = req ? `${req.protocol}://${req.get('Host')}` : '';
1818
const httpLink = createHttpLink({
1919
uri: `${baseUrl}/graphql`,
@@ -39,7 +39,7 @@ const create = (initialState: any, {getToken}: any, req?: any) => {
3939
});
4040
};
4141

42-
export const initApollo = (initialState: any, options: any, req?: any) => {
42+
export const initApollo = (initialState: any, options: {getToken: () => string}, req?: any) => {
4343
// Make sure to create a new client for every server-side request so that data
4444
// isn't shared between connections (which would be bad)
4545
if (!process.browser) {

client/with/withApollo.tsx

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as React from 'react';
2-
import {NextDocumentContext} from 'next/document';
32
import Head from 'next/head';
3+
import {AppComponentContext} from 'next/app';
4+
import {ApolloClient} from 'apollo-boost';
45
import {getDataFromTree} from 'react-apollo';
56
import * as cookie from 'cookie';
67
import {initApollo} from './initApollo';
@@ -9,13 +10,13 @@ declare const process: any;
910

1011
const parseCookies = (req?: any, options = {}) => cookie.parse(req ? req.headers.cookie || '' : document.cookie, options);
1112

12-
type AppType = React.ComponentClass<any> & {getInitialProps?: (ctx: NextDocumentContext) => any};
13+
type AppType = React.ComponentClass<any> & {getInitialProps?: (ctx: AppComponentContext) => any};
1314

1415
export const withApollo = (App: AppType): React.ComponentClass<any> => {
1516
return class PageWithApollo extends React.Component<any> {
16-
private apolloClient: any;
17+
private readonly apolloClient: any;
1718

18-
static async getInitialProps(ctx: any) {
19+
static async getInitialProps(ctx: AppComponentContext & {ctx: {apolloClient: ApolloClient<any>}}) {
1920
const {
2021
Component,
2122
router,
@@ -26,17 +27,14 @@ export const withApollo = (App: AppType): React.ComponentClass<any> => {
2627

2728
ctx.ctx.apolloClient = apollo;
2829

29-
let appProps = {};
30-
if (App.getInitialProps) {
31-
appProps = await App.getInitialProps(ctx);
32-
}
33-
3430
if (res && res.finished) {
3531
// When redirecting, the response is finished.
3632
// No point in continuing to render
3733
return {};
3834
}
3935

36+
const appProps = App.getInitialProps ? await App.getInitialProps(ctx) : {};
37+
4038
// Run all graphql queries in the component tree
4139
// and extract the resulting data
4240
try {
@@ -55,12 +53,10 @@ export const withApollo = (App: AppType): React.ComponentClass<any> => {
5553
Head.rewind();
5654
}
5755

58-
// Extract query data from the Apollo's store
59-
const apolloState = apollo.cache.extract();
60-
6156
return {
6257
...appProps,
63-
apolloState,
58+
// Extract query data from the Apollo's store
59+
apolloState: apollo.cache.extract(),
6460
};
6561
}
6662

client/with/withAuthAdmin.tsx

Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
import * as React from 'react';
2+
import {ApolloClient, ApolloQueryResult} from 'apollo-boost';
23
import gql from 'graphql-tag';
34
import Router from 'next/router';
45
import cookie from 'cookie';
6+
import {Account, Query} from '@graphql-model';
7+
import {NextDocumentContext} from 'next/document';
58

6-
const checkLoggedIn = (apolloClient: any): Promise<{loggedInUser: any}> => {
9+
interface LoggedInUserResponse {
10+
readonly loggedInUser: Pick<Account, 'id' | 'firstName' | 'lastName'>;
11+
}
12+
13+
const checkLoggedIn = (apolloClient: ApolloClient<any>): Promise<Partial<LoggedInUserResponse>> => {
714
return apolloClient
815
.query({
916
query: gql`
@@ -16,54 +23,54 @@ const checkLoggedIn = (apolloClient: any): Promise<{loggedInUser: any}> => {
1623
}
1724
`,
1825
})
19-
.then(({data}: any) => {
20-
return {loggedInUser: data};
26+
.then(({data}: ApolloQueryResult<Query>) => {
27+
if (!data || !data.me) {
28+
throw new Error('User is not logged');
29+
}
30+
return {loggedInUser: data.me};
2131
})
2232
.catch(() => {
2333
// Fail gracefully
24-
return {loggedInUser: {}};
34+
return {loggedInUser: undefined};
2535
});
2636
};
2737

28-
const redirect = (context: any, target: string) => {
29-
if (context.res) {
30-
// server
31-
// 303: "See other"
38+
const redirect = async (target: string, context?: NextDocumentContext): Promise<boolean> => {
39+
if (context && context.res) {
3240
context.res.writeHead(303, {Location: target});
3341
context.res.end();
42+
return true;
3443
} else {
35-
// In the browser, we just pretend like this never even happened ;)
36-
Router.replace(target);
44+
return await Router.replace(target);
3745
}
3846
};
3947

40-
export const withAuthAdmin = (BaseComponent: any) => {
41-
return class extends React.Component {
42-
signout = (apolloClient: any) => () => {
48+
export interface WithAuthAdminProps extends LoggedInUserResponse {
49+
readonly logout: (client: ApolloClient<any>) => () => Promise<void>;
50+
}
51+
52+
export const withAuthAdmin = (BaseComponent: React.ComponentType<WithAuthAdminProps>) => {
53+
return class extends React.Component<LoggedInUserResponse> {
54+
handleOnLogout = (apolloClient: ApolloClient<any>) => async () => {
4355
document.cookie = cookie.serialize('token', '', {
4456
maxAge: -1, // Expire the cookie immediately
4557
});
46-
47-
// Force a reload of all the current queries now that the user is
48-
// logged in, so we don't accidentally leave any state around.
49-
apolloClient.cache.reset().then(() => {
50-
// Redirect to a more useful page when signed out
51-
redirect({}, '/login');
52-
});
58+
await apolloClient.cache.reset();
59+
await redirect('/login');
5360
};
5461

55-
static async getInitialProps(context: any, _: any) {
62+
static async getInitialProps(context: NextDocumentContext & {apolloClient: ApolloClient<any>}) {
5663
const {loggedInUser} = await checkLoggedIn(context.apolloClient);
57-
if (!loggedInUser.me) {
64+
if (!loggedInUser) {
5865
// If not signed in, send them somewhere more useful
59-
redirect(context, '/login');
66+
await redirect('/login', context);
6067
}
6168

6269
return {loggedInUser};
6370
}
6471

6572
render() {
66-
return <BaseComponent {...this.props} logout={this.signout} />;
73+
return <BaseComponent {...this.props} logout={this.handleOnLogout} />;
6774
}
6875
};
6976
};

package-lock.json

Lines changed: 29 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,29 +48,29 @@
4848
"dependencies": {
4949
"@material-ui/core": "1.4.0",
5050
"@material-ui/icons": "1.1.0",
51-
"apollo-boost": "^0.1.10",
52-
"apollo-link-context": "^1.0.8",
53-
"apollo-server-express": "^2.0.0",
54-
"autoprefixer": "^9.0.1",
55-
"cookie": "^0.3.1",
51+
"apollo-boost": "0.1.10",
52+
"apollo-link-context": "1.0.8",
53+
"apollo-server-express": "2.0.0",
54+
"autoprefixer": "9.0.1",
55+
"cookie": "0.3.1",
5656
"dotenv": "6.0.0",
5757
"express": "4.16.3",
5858
"graphql": "0.13.2",
5959
"graphql-import": "0.6.0",
6060
"graphql-tag": "2.9.2",
6161
"graphql-tools": "3.0.5",
6262
"intl": "1.2.5",
63-
"isomorphic-unfetch": "^2.1.0",
63+
"isomorphic-unfetch": "2.1.0",
6464
"next": "6.1.1",
65-
"nprogress": "^0.2.0",
65+
"nprogress": "0.2.0",
6666
"react": "16.4.1",
67-
"react-apollo": "^2.1.9",
67+
"react-apollo": "2.1.9",
6868
"react-dom": "16.4.1",
6969
"react-intl": "2.4.0"
7070
},
7171
"devDependencies": {
72-
"@types/autoprefixer": "^6.7.3",
73-
"@types/cookie": "^0.3.1",
72+
"@types/autoprefixer": "6.7.3",
73+
"@types/cookie": "0.3.1",
7474
"@types/express": "4.16.0",
7575
"@types/glob": "5.0.35",
7676
"@types/intl": "1.2.0",
@@ -85,7 +85,7 @@
8585
"babel-plugin-react-intl": "2.4.0",
8686
"coveralls": "3.0.2",
8787
"fork-ts-checker-webpack-plugin": "0.4.3",
88-
"glob": "^7.1.2",
88+
"glob": "7.1.2",
8989
"graphql-code-generator": "0.10.3",
9090
"graphql-codegen-typescript-template": "0.10.3",
9191
"husky": "0.14.3",

pages/admin/index.tsx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
import * as React from 'react';
22
import {ApolloConsumer} from 'react-apollo';
3-
import {withAuthAdmin} from '../../client/with';
3+
import {withAuthAdmin, WithAuthAdminProps} from '../../client/with';
44

5-
class Page extends React.Component<any> {
5+
class Page extends React.Component<WithAuthAdminProps> {
66
render() {
7-
const {logout} = this.props;
7+
const {logout, loggedInUser} = this.props;
88
return (
99
<ApolloConsumer>
1010
{(client) => (
1111
<div>
12-
Hello {this.props.loggedInUser.me.firstName}!<br />
12+
Hello {loggedInUser.firstName}!<br />
1313
<button onClick={logout(client)}>Sign out</button>
1414
</div>
1515
)}

0 commit comments

Comments
 (0)