Repository: Shopify/shopify-node-app Branch: master Commit: feb4e29988c0 Files: 20 Total size: 21.1 KB Directory structure: gitextract_sosbrxnk/ ├── .babelrc ├── .eslintrc ├── .gitignore ├── .nvmrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── bin/ │ └── www.js ├── client/ │ ├── App.js │ ├── actions/ │ │ └── index.js │ ├── components/ │ │ ├── ApiConsole.js │ │ └── VerbPicker.js │ ├── index.js │ └── store/ │ └── index.js ├── config/ │ └── webpack.config.js ├── package.json └── server/ ├── index.js └── views/ ├── app.ejs ├── error.ejs └── install.ejs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc ================================================ { "presets": [ "react", "env", "es2015" ], "plugins": [ "react-hot-loader/babel", "transform-object-rest-spread", "transform-class-properties" ] } ================================================ FILE: .eslintrc ================================================ { "plugins": [ "prettier" ], "rules": { "prettier/prettier": "error" }, "extends": [ "prettier" ] } ================================================ FILE: .gitignore ================================================ .env .DS_Store assets/ node_modules/ dump.rdb main.js db.sqlite3 ================================================ FILE: .nvmrc ================================================ 8.1.0 ================================================ FILE: CONTRIBUTING.md ================================================ # How to contribute This project is deprecated. Contributions will not be accepted. ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2017 Shopify Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # This project is deprecated This project is deprecated and not supported by Shopify. This project contains **out-of-date dependencies** with **known security vulnerabilities** and **should not be used in a production environment**. If you are looking for information about building a Shopify app with Node.js, please see our [Build a Shopify App with Node.js and React](https://developers.shopify.com/tutorials/build-a-shopify-app-with-node-and-react) tutorial. ================================================ FILE: bin/www.js ================================================ #!/usr/bin/env node require('dotenv').config(); const chalk = require('chalk'); const http = require('http'); const app = require('../server'); const port = process.env.SHOPIFY_APP_PORT || '3000'; app.set('port', port); const server = http.createServer(app); server.listen(port, err => { if (err) { return console.log('😫', chalk.red(err)); } console.log(`🚀 Now listening on port ${chalk.green(port)}`); }); ================================================ FILE: client/App.js ================================================ import React, { Component } from 'react'; import { Page, AppProvider } from '@shopify/polaris'; import ApiConsole from './components/ApiConsole' class App extends Component { render() { const { apiKey, shopOrigin } = window; return ( ); } } export default App; ================================================ FILE: client/actions/index.js ================================================ export function updateVerb(verb) { return { type: 'UPDATE_VERB', payload: { verb, }, }; } export function updatePath(path) { return { type: 'UPDATE_PATH', payload: { path, }, }; } export function updateParams(params) { return { type: 'UPDATE_PARAMS', payload: { params, }, }; } export function sendRequest(requestFields) { const { verb, path, params } = requestFields; const fetchOptions = { method: verb, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, credentials: 'include', } if (verb !== 'GET') { fetchOptions['body'] = params } return dispatch => { dispatch(requestStartAction()); return fetch(`/shopify/api${path}`, fetchOptions) .then(response => response.json()) .then(json => dispatch(requestCompleteAction(json))) .catch(error => { dispatch(requestErrorAction(error)); }); }; } function requestStartAction() { return { type: 'REQUEST_START', payload: {}, }; } function requestCompleteAction(json) { const responseBody = JSON.stringify(json, null, 2); return { type: 'REQUEST_COMPLETE', payload: { responseBody }, }; } function requestErrorAction(requestError) { return { type: 'REQUEST_ERROR', payload: { requestError, }, }; } ================================================ FILE: client/components/ApiConsole.js ================================================ import React, { Component} from 'react'; import { connect } from 'react-redux'; import { Layout, Stack, Card, TextField, Button } from '@shopify/polaris'; import ObjectInspector from 'react-object-inspector'; import { updatePath, updateParams, sendRequest } from '../actions'; import VerbPicker from './VerbPicker'; class ApiConsole extends Component { render() { return ( { this.renderForm() } { this.renderResponse() } ) } renderForm() { const { dispatch, requestFields } = this.props; return (
dispatch(updatePath(path))} /> {this.renderParams()}
) } renderParams() { const { dispatch, requestFields } = this.props; if (requestFields.verb === 'GET') { return null; } else { return ( dispatch(updateParams(params))} multiline={12} /> ); } } renderResponse() { const { requestInProgress, requestError, responseBody } = this.props; if (responseBody === '') { return null; } if (requestInProgress) { return ( 'requesting...'; ) } const data = JSON.parse(responseBody) return (
) } } function mapStateToProps({ requestFields, requestInProgress, requestError, responseBody, }) { return { requestFields, requestInProgress, requestError, responseBody, }; } export default connect(mapStateToProps)(ApiConsole); ================================================ FILE: client/components/VerbPicker.js ================================================ import React, { Component} from 'react'; import { connect } from 'react-redux'; import { Popover, ActionList, Button } from '@shopify/polaris'; import { updateVerb } from '../actions'; class VerbPicker extends Component { constructor(props) { super(props) this.state = { opened: false } } toggleOpened() { this.setState({ opened: !this.state.opened }) } close() { this.setState({ opened: false }) } onAction(verb) { this.props.dispatch(updateVerb(verb)) this.close() } render() { const button = ( ) return ( this.close()}> { return { content: verb, onAction: () => this.onAction(verb) } })} /> ) } } export default connect()(VerbPicker); ================================================ FILE: client/index.js ================================================ import * as React from 'react'; import 'isomorphic-fetch'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { AppContainer } from 'react-hot-loader'; import store from '../client/store'; import App from './App'; function renderApp() { render( , document.getElementById('root') ); } renderApp(); if (module.hot) { module.hot.accept(); } ================================================ FILE: client/store/index.js ================================================ import { createStore, applyMiddleware } from 'redux'; import thunkMiddleware from 'redux-thunk'; import logger from 'redux-logger'; const requestFields = { verb: 'POST', path: '/products.json', params: JSON.stringify({ product: { title: "Burton Custom Freestyle 151", body_html: "Good snowboard!<\/strong>", vendor: "Burton", product_type: "Snowboard" } }, null, 2) }; const initState = { requestFields, requestInProgress: false, requestError: null, responseBody: '', }; function reducer(state = initState, action) { switch (action.type) { case 'UPDATE_VERB': return { ...state, responseBody: '', requestFields: { ...state.requestFields, verb: action.payload.verb, }, }; case 'UPDATE_PATH': return { ...state, responseBody: '', requestFields: { ...state.requestFields, path: action.payload.path, }, }; case 'UPDATE_PARAMS': return { ...state, responseBody: '', requestFields: { ...state.requestFields, params: action.payload.params, }, }; case 'REQUEST_START': return { ...state, requestInProgress: true, requestError: null, responseBody: '' }; case 'REQUEST_COMPLETE': return { ...state, requestInProgress: false, requestError: null, responseBody: action.payload.responseBody }; case 'REQUEST_ERROR': return { ...state, requestInProgress: false, requestError: action.payload.requestError, }; default: return state; } } const middleware = applyMiddleware(thunkMiddleware, logger); const store = createStore(reducer, middleware); export default store; ================================================ FILE: config/webpack.config.js ================================================ const path = require('path'); const webpack = require('webpack'); const autoprefixer = require('autoprefixer'); const isDevelopment = process.env.NODE_ENV !== 'production'; const sourceMap = isDevelopment; const plugins = isDevelopment ? [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development'), }), new webpack.HotModuleReplacementPlugin(), ] : [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, }, minimize: true, }), ]; const extraEntryFiles = isDevelopment ? ['react-hot-loader/patch', 'webpack-hot-middleware/client'] : []; module.exports = { plugins, target: 'web', devtool: 'eval', entry: { main: [ ...extraEntryFiles, '@shopify/polaris/styles.css', path.resolve(__dirname, '../client/index.js'), ], }, output: { filename: '[name].js', path: path.resolve(__dirname, '../assets'), publicPath: '/assets/', libraryTarget: 'var', }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, }, { test: /\.css$/, exclude: /node_modules/, loaders: [ { loader: 'style-loader', }, { loader: 'css-loader', query: { sourceMap, modules: true, importLoaders: 1, localIdentName: '[name]-[local]_[hash:base64:5]', }, }, { loader: 'postcss-loader', options: { plugins: () => autoprefixer(), sourceMap, }, }, ], }, { test: /\.css$/, include: path.resolve(__dirname, '../node_modules/@shopify/polaris'), loaders: [ { loader: 'style-loader', }, { loader: 'css-loader', query: { sourceMap, modules: true, importLoaders: 1, localIdentName: '[local]', }, }, ], }, ], }, }; ================================================ FILE: package.json ================================================ { "name": "shopify-node-app", "version": "0.0.0", "private": true, "scripts": { "prod": "yarn run clean && yarn run build && cross-env NODE_ENV=production yarn run start", "dev": "cross-env NODE_ENV=development yarn run start", "start": "nodemon ./bin/www", "build": "cross-env NODE_ENV=production webpack --config ./config/webpack.config.js --progress --profile --colors", "clean": "rm -rf ./assets && mkdir ./assets", "pretty": "prettier --single-quote --trailing-comma es5 --write {client,bin,config,server}{/*,/**/*}.js", "precommit": "yarn run pretty" }, "engines": { "node": ">= 8.1.0" }, "browsers": [ "last 3 chrome versions", "last 3 firefox versions", "last 2 versions", "safari >= 8", "ios >= 8", "ie >= 11", "explorermobile >= 11", "android >= 4.4" ], "dependencies": { "@shopify/polaris": "^2.3.1", "@shopify/shopify-express": "^1.0.0-alpha.7", "chalk": "^1.1.3", "connect-redis": "^3.3.0", "cross-env": "^5.1.3", "debug": "~2.6.3", "dotenv": "^4.0.0", "ejs": "~2.5.6", "express": "~4.15.2", "express-session": "^1.15.3", "knex": "^0.13.0", "morgan": "~1.8.1", "react": "^16.4.0", "react-dom": "^16.4.0", "nodemon": "^1.17.1", "react-object-inspector": "^0.2.1", "react-redux": "^5.0.5", "redis": "^2.7.1", "redux": "^3.6.0", "redux-logger": "^3.0.6", "redux-thunk": "^2.2.0", "shopify-api-node": "^2.11.0", "sqlite3": "^3.1.9", "url": "^0.11.0", "webpack-hot-middleware": "^2.18.0", "webpack-middleware": "^1.5.1" }, "devDependencies": { "autoprefixer": "^7.1.1", "babel-core": "^6.25.0", "babel-loader": "^7.0.0", "babel-plugin-transform-object-rest-spread": "^6.23.0", "babel-plugin-transform-class-properties": "^6.24.1", "babel-preset-env": "^1.5.2", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "css-loader": "^0.28.4", "eslint": "3.19.0", "eslint-plugin-prettier": "^2.1.2", "global": "^4.3.2", "postcss-loader": "^2.0.6", "prettier": "^1.5.2", "react-hot-loader": "^3.0.0-beta.7", "style-loader": "^0.18.2", "webpack": "^2.6.1", "webpack-dev-server": "^2.4.5" } } ================================================ FILE: server/index.js ================================================ require('isomorphic-fetch'); require('dotenv').config(); const fs = require('fs'); const express = require('express'); const session = require('express-session'); const RedisStore = require('connect-redis')(session); const path = require('path'); const logger = require('morgan'); const webpack = require('webpack'); const webpackMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const config = require('../config/webpack.config.js'); const ShopifyAPIClient = require('shopify-api-node'); const ShopifyExpress = require('@shopify/shopify-express'); const {MemoryStrategy} = require('@shopify/shopify-express/strategies'); const { SHOPIFY_APP_KEY, SHOPIFY_APP_HOST, SHOPIFY_APP_SECRET, NODE_ENV, } = process.env; const shopifyConfig = { host: SHOPIFY_APP_HOST, apiKey: SHOPIFY_APP_KEY, secret: SHOPIFY_APP_SECRET, scope: ['write_orders, write_products'], shopStore: new MemoryStrategy(), afterAuth(request, response) { const { session: { accessToken, shop } } = request; registerWebhook(shop, accessToken, { topic: 'orders/create', address: `${SHOPIFY_APP_HOST}/order-create`, format: 'json' }); return response.redirect('/'); }, }; const registerWebhook = function(shopDomain, accessToken, webhook) { const shopify = new ShopifyAPIClient({ shopName: shopDomain, accessToken: accessToken }); shopify.webhook.create(webhook).then( response => console.log(`webhook '${webhook.topic}' created`), err => console.log(`Error creating webhook '${webhook.topic}'. ${JSON.stringify(err.response.body)}`) ); } const app = express(); const isDevelopment = NODE_ENV !== 'production'; app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use( session({ store: isDevelopment ? undefined : new RedisStore(), secret: SHOPIFY_APP_SECRET, resave: true, saveUninitialized: false, }) ); // Run webpack hot reloading in dev if (isDevelopment) { const compiler = webpack(config); const middleware = webpackMiddleware(compiler, { hot: true, inline: true, publicPath: config.output.publicPath, contentBase: 'src', stats: { colors: true, hash: false, timings: true, chunks: false, chunkModules: false, modules: false, }, }); app.use(middleware); app.use(webpackHotMiddleware(compiler)); } else { const staticPath = path.resolve(__dirname, '../assets'); app.use('/assets', express.static(staticPath)); } // Install app.get('/install', (req, res) => res.render('install')); // Create shopify middlewares and router const shopify = ShopifyExpress(shopifyConfig); // Mount Shopify Routes const {routes, middleware} = shopify; const {withShop, withWebhook} = middleware; app.use('/shopify', routes); // Client app.get('/', withShop({authBaseUrl: '/shopify'}), function(request, response) { const { session: { shop, accessToken } } = request; response.render('app', { title: 'Shopify Node App', apiKey: shopifyConfig.apiKey, shop: shop, }); }); app.post('/order-create', withWebhook((error, request) => { if (error) { console.error(error); return; } console.log('We got a webhook!'); console.log('Details: ', request.webhook); console.log('Body:', request.body); })); // Error Handlers app.use(function(req, res, next) { const err = new Error('Not Found'); err.status = 404; next(err); }); app.use(function(error, request, response, next) { response.locals.message = error.message; response.locals.error = request.app.get('env') === 'development' ? error : {}; response.status(error.status || 500); response.render('error'); }); module.exports = app; ================================================ FILE: server/views/app.ejs ================================================ <%= title %>
================================================ FILE: server/views/error.ejs ================================================

<%= message %>

<%= error.status %>

<%= error.stack %>
================================================ FILE: server/views/install.ejs ================================================ Shopify Node App

Shopify Node App – Installation