Skip to content

Commit

Permalink
book/8-end Stripe API and ESLint fix
Browse files Browse the repository at this point in the history
  • Loading branch information
tima101 committed Aug 21, 2020
1 parent a73e271 commit f7b4ed1
Show file tree
Hide file tree
Showing 19 changed files with 416 additions and 317 deletions.
50 changes: 0 additions & 50 deletions .eslintrc.js

This file was deleted.

7 changes: 3 additions & 4 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"recommendations": [
"dbaeumer.vscode-eslint"
]
}
"recommendations": ["dbaeumer.vscode-eslint"]
}

16 changes: 14 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
{
"window.zoomLevel": -1,
"window.zoomLevel": 0,
"files.autoSave": "afterDelay",
"git.enableSmartCommit": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"eslint.enable": true,
"eslint.alwaysShowStatus": true,
"eslint.validate": [
"javascript",
],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"eslint.workingDirectories": [
{
"directory": "./book/8-end/",
"changeProcessCWD": true
},
],
}
27 changes: 16 additions & 11 deletions book/8-end/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ module.exports = {
},
plugins: ['react', 'jsx-a11y', 'import', 'prettier'],
rules: {
'prettier/prettier': [
'error',
{
singleQuote: true,
trailingComma: 'all',
arrowParens: 'always',
printWidth: 100,
semi: true
},
],
'camelcase': 'off',
'max-len': ['error', 100],
'no-underscore-dangle': ['error', { allow: ['_id'] }],
'no-mixed-operators': 'off',
Expand All @@ -28,23 +39,17 @@ module.exports = {
],
'import/prefer-default-export': 'off',
'jsx-a11y/anchor-is-valid': 'off',
'react/jsx-wrap-multilines': 'off',
'react/destructuring-assignment': 'off',
'react/no-danger': 'off',
'react/jsx-one-expression-per-line': 'off',
'react/jsx-props-no-spreading': 'off',
'react/react-in-jsx-scope': 'off',
'react/jsx-filename-extension': [
'error',
{
extensions: ['.js'],
},
],
'prefer-arrow-callback': 'error',
'prettier/prettier': [
'error',
{
singleQuote: true,
trailingComma: 'all',
arrowParens: 'always',
printWidth: 100,
semi: true
},
],
},
};
159 changes: 74 additions & 85 deletions book/8-end/components/customer/BuyButton.js
Original file line number Diff line number Diff line change
@@ -1,59 +1,52 @@
import React from 'react';
import PropTypes from 'prop-types';
import StripeCheckout from 'react-stripe-checkout';
import NProgress from 'nprogress';

import Button from '@material-ui/core/Button';
import Link from 'next/link';
import { loadStripe } from '@stripe/stripe-js';

import { fetchCheckoutSession } from '../../lib/api/customer';
import getRootUrl from '../lib/api/getRootUrl';

import { buyBook } from '../../lib/api/customer';
import notify from '../../lib/notifier';
import env from '../../lib/env';

const { StripePublishableKey } = env;
const dev = process.env.NODE_ENV !== 'production';

const styleBuyButton = {
margin: '20px 20px 20px 0px',
font: '14px Muli',
};
// console.log('StripePublishableKey', StripePublishableKey);

class BuyButton extends React.Component {
static propTypes = {
book: PropTypes.shape({
_id: PropTypes.string.isRequired,
}),
user: PropTypes.shape({
_id: PropTypes.string.isRequired,
}),
showModal: PropTypes.bool,
};

static defaultProps = {
book: null,
user: null,
showModal: false,
};
const stripePromise = loadStripe(process.env.StripePublishableKey);
const ROOT_URL = getRootUrl();

constructor(props) {
super(props);
const styleBuyButton = {
margin: '10px 20px 0px 0px',
font: '14px Roboto',
};

this.state = {
showModal: !!props.showModal,
};
class BuyButton extends React.PureComponent {
componentDidMount() {
if (this.props.redirectToCheckout) {
this.handleCheckoutClick();
}
}

onToken = async (token) => {
handleCheckoutClick = async () => {
NProgress.start();
const { book } = this.props;
this.setState({ showModal: false });

try {
await buyBook({ stripeToken: token, id: book._id });
notify('Success!');
window.location.reload(true);
NProgress.done();
const { book } = this.props;
const { sessionId } = await fetchCheckoutSession({ bookId: book._id, nextUrl: document.location.pathname });

// When the customer clicks on the button, redirect them to Checkout.
const stripe = await stripePromise;
const { error } = await stripe.redirectToCheckout({ sessionId });

if (error) {
notify(error);
}
} catch (err) {
NProgress.done();
notify(err);
} finally {
NProgress.done();
}
};

Expand All @@ -62,13 +55,12 @@ class BuyButton extends React.Component {

if (!user) {
const redirectUrl = `${window.location.pathname}?buy=1`;
window.location.href = `/auth/google?redirectUrl=${redirectUrl}`;
window.location.href = `${ROOT_URL}/auth/google?redirectUrl=${redirectUrl}`;
}
};

render() {
const { book, user } = this.props;
const { showModal } = this.state;

if (!book) {
return null;
Expand All @@ -79,63 +71,60 @@ class BuyButton extends React.Component {
<div>
<Button
variant="contained"
style={styleBuyButton}
color="primary"
style={styleBuyButton}
onClick={this.onLoginClicked}
>
Buy book for ${book.price}
{`Buy book for $${book.price}`}
</Button>
{book.slug === 'builder-book' ? (
<Link as="/book-reviews" href="/book-reviews">
<Button variant="outlined" style={styleBuyButton}>
See Reviews
</Button>
</Link>
) : null}
<p style={{ verticalAlign: 'middle', fontSize: '15px' }}>{book.textNearButton}</p>
<hr />
</div>
);
}

return (
<StripeCheckout
stripeKey={StripePublishableKey}
token={this.onToken}
name={book.name}
amount={book.price * 100}
email={user.email}
desktopShowModal={showModal || null}
>
<Button variant="contained" style={styleBuyButton} color="primary">
Buy book for ${book.price}
<div>
<Button
variant="contained"
color="primary"
style={styleBuyButton}
onClick={this.handleCheckoutClick}
>
{`Buy book for $${book.price}`}
</Button>
</StripeCheckout>
<p style={{ verticalAlign: 'middle', fontSize: '15px' }}>{book.textNearButton}</p>
<hr />
</div>
);
}
}

export default BuyButton;


// new Stripe API
// apiVersion: '2020-03-02'
// import { loadStripe } from '@stripe/stripe-js';


// private handleCheckoutClick = async (mode: 'subscription' | 'setup') => {
// try {
// const { currentTeam } = this.props.store;

// NProgress.start();
// this.setState({ disabled: true });

// const { sessionId } = await fetchCheckoutSessionApiMethod({ mode, teamId: currentTeam._id });
BuyButton.propTypes = {
book: PropTypes.shape({
_id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
slug: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
textNearButton: PropTypes.string,
}),
user: PropTypes.shape({
_id: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
}),
redirectToCheckout: PropTypes.bool,
};

// // When the customer clicks on the button, redirect them to Checkout.
// const stripe = await stripePromise;
// const { error } = await stripe.redirectToCheckout({ sessionId });
BuyButton.defaultProps = {
book: null,
user: null,
redirectToCheckout: false,
};

// if (error) {
// notify(error);
// console.error(error);
// }
// } catch (err) {
// notify(err);
// console.error(err);
// } finally {
// this.setState({ disabled: false });
// NProgress.done();
// }
// };
export default BuyButton;
10 changes: 5 additions & 5 deletions book/8-end/lib/api/customer.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@ import sendRequest from './sendRequest';

const BASE_PATH = '/api/v1/customer';

export const buyBook = ({ id, stripeToken }) =>
sendRequest(`${BASE_PATH}/buy-book`, {
body: JSON.stringify({ id, stripeToken }),
});

export const getMyBookList = (options = {}) =>
sendRequest(
`${BASE_PATH}/my-books`,
Expand All @@ -17,3 +12,8 @@ export const getMyBookList = (options = {}) =>
options,
),
);

export const fetchCheckoutSession = ({ bookId, nextUrl }) =>
sendRequestAndGetResponse(`${BASE_PATH}/stripe/fetch-checkout-session`, {
body: JSON.stringify({ bookId, nextUrl }),
});
4 changes: 2 additions & 2 deletions book/8-end/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@
"winston": "3.3.3"
},
"devDependencies": {
"babel-eslint": "10.1.0",
"eslint": "7.7.0",
"babel-eslint": "10.0.3",
"eslint": "6.7.2",
"eslint-config-airbnb": "18.2.0",
"eslint-config-prettier": "6.11.0",
"eslint-plugin-import": "2.22.0",
Expand Down
2 changes: 1 addition & 1 deletion book/8-end/server/api/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const express = require('express');
const Book = require('../models/Book');
const User = require('../models/User');
const { getRepos } = require('../github');
const logger = require('../logs');
const logger = require('../logger');

const router = express.Router();

Expand Down
Loading

0 comments on commit f7b4ed1

Please sign in to comment.