=

first commit

Showing 145 changed files with 4694 additions and 0 deletions
node_modules
tmp
lib
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/server/src/routers/graphql/Mutation/createPost.ts",
"outFiles": [
"${workspaceFolder}/**/*.js"
]
}
]
}
\ No newline at end of file
{
}
\ No newline at end of file
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
/node_modules
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
This diff could not be displayed because it is too large.
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
var dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
`${paths.dotenv}.${NODE_ENV}`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
paths.dotenv,
].filter(Boolean);
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile,
})
);
}
});
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether we’re running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
}
);
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce(
(env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
},
{}
),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;
'use strict';
// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'cssTransform';
},
};
'use strict';
const path = require('path');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
return `module.exports = ${JSON.stringify(path.basename(filename))};`;
},
};
// Copyright 2004-present Facebook. All Rights Reserved.
'use strict';
const tsJestPreprocessor = require('ts-jest/preprocessor');
module.exports = tsJestPreprocessor;
'use strict';
const path = require('path');
const fs = require('fs');
const url = require('url');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
const envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return `${path}/`;
} else {
return path;
}
}
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl = envPublicUrl ||
(publicUrl ? url.parse(publicUrl).pathname : '/');
return ensureSlash(servedUrl, true);
}
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveApp('src/index.tsx'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveApp('src/setupTests.ts'),
appNodeModules: resolveApp('node_modules'),
appTsConfig: resolveApp('tsconfig.json'),
appTsLint: resolveApp('tslint.json'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
};
'use strict';
if (typeof Promise === 'undefined') {
// Rejection tracking prevents a common issue where React gets into an
// inconsistent state due to an error, but it gets swallowed by a Promise,
// and the user has no idea what causes React's erratic future behavior.
require('promise/lib/rejection-tracking').enable();
window.Promise = require('promise/lib/es6-extensions.js');
}
// fetch() polyfill for making API calls.
require('whatwg-fetch');
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');
// In tests, polyfill requestAnimationFrame since jsdom doesn't provide it yet.
// We don't polyfill it in the browser--this is user's responsibility.
if (process.env.NODE_ENV === 'test') {
require('raf').polyfill(global);
}
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const publicPath = '/';
const publicUrl = '';
const env = getClientEnvironment(publicUrl);
module.exports = {
devtool: 'cheap-module-source-map',
entry: [
require.resolve('./polyfills'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs,
],
output: {
pathinfo: true,
filename: 'static/js/bundle.js',
chunkFilename: 'static/js/[name].chunk.js',
publicPath: publicPath,
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
modules: ['src', 'node_modules', paths.appNodeModules].concat(
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
extensions: [
'.mjs',
'.web.ts',
'.ts',
'.web.tsx',
'.tsx',
'.web.js',
'.js',
'.json',
'.web.jsx',
'.jsx',
],
plugins: [
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
new TsconfigPathsPlugin({ configFile: paths.appTsConfig }),
],
},
module: {
strictExportPresence: true,
rules: [
{
test: /\.(js|jsx|mjs)$/,
loader: require.resolve('source-map-loader'),
enforce: 'pre',
include: paths.appSrc,
},
{
oneOf: [
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
compact: true,
},
},
{
test: /\.(ts|tsx)$/,
include: paths.appSrc,
use: [
{
loader: require.resolve('ts-loader'),
options: {
transpileOnly: true,
},
},
],
},
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
{
test: /\.scss$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
{
loader: require.resolve('sass-loader'),
options: {
// includePaths: ["absolute/path/a", "absolute/path/b"]
}
}
],
},
{
test: /\.(gql|graphql)$/,
loader: require.resolve('graphql-tag/loader'),
},
{
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
],
},
plugins: [
new InterpolateHtmlPlugin(env.raw),
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
new webpack.NamedModulesPlugin(),
new webpack.DefinePlugin(env.stringified),
new webpack.HotModuleReplacementPlugin(),
new CaseSensitivePathsPlugin(),
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new ForkTsCheckerWebpackPlugin({
async: false,
watch: paths.appSrc,
tsconfig: paths.appTsConfig,
tslint: paths.appTsLint,
}),
],
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
performance: {
hints: false,
},
};
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
? // Making sure that the publicPath goes back to to build folder.
{ publicPath: Array(cssFilename.split('/').length).join('../') }
: {};
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
// Don't attempt to continue if there are any errors.
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: shouldUseSourceMap ? 'source-map' : false,
// In production, we only want to load the polyfills and the app code.
entry: [require.resolve('./polyfills'), paths.appIndexJs],
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['src', 'node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: [
'.mjs',
'.web.ts',
'.ts',
'.web.tsx',
'.tsx',
'.web.js',
'.js',
'.json',
'.web.jsx',
'.jsx',
],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
new TsconfigPathsPlugin({ configFile: paths.appTsConfig }),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
{
test: /\.(js|jsx|mjs)$/,
loader: require.resolve('source-map-loader'),
enforce: 'pre',
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works just like "file" loader but it also embeds
// assets smaller than specified size as data URLs to avoid requests.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
compact: true,
},
},
// Compile .tsx?
{
test: /\.(ts|tsx)$/,
include: paths.appSrc,
use: [
{
loader: require.resolve('ts-loader'),
options: {
// disable type checker - we will use it in fork plugin
transpileOnly: true,
},
},
],
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
Object.assign(
{
fallback: {
loader: require.resolve('style-loader'),
options: {
hmr: false,
},
},
use: [
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
minimize: true,
sourceMap: shouldUseSourceMap,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
extractTextPluginOptions
)
),
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
// "file" loader makes sure assets end up in the `build` folder.
// When you `import` an asset, you get its filename.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Minify the code.
new UglifyJsPlugin({
uglifyOptions: {
parse: {
// we want uglify-js to parse ecma 8 code. However we want it to output
// ecma 5 compliant code, to avoid issues with older browsers, this is
// whey we put `ecma: 5` to the compress and output section
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
// Use multi-process parallel running to improve the build speed
// Default number of concurrent runs: os.cpus().length - 1
parallel: true,
// Enable file caching
cache: true,
sourceMap: shouldUseSourceMap,
}), // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
new ExtractTextPlugin({
filename: cssFilename,
}),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json',
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
new SWPrecacheWebpackPlugin({
// By default, a cache-busting query parameter is appended to requests
// used to populate the caches, to ensure the responses are fresh.
// If a URL is already hashed by Webpack, then there is no concern
// about it being stale, and the cache-busting can be skipped.
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: 'service-worker.js',
logger(message) {
if (message.indexOf('Total precache size is') === 0) {
// This message occurs for every build and is a bit too noisy.
return;
}
if (message.indexOf('Skipping static resource') === 0) {
// This message obscures real errors so we ignore it.
// https://github.com/facebookincubator/create-react-app/issues/2612
return;
}
console.log(message);
},
minify: true,
// For unknown URLs, fallback to the index page
navigateFallback: publicUrl + '/index.html',
// Ignores URLs starting from /__ (useful for Firebase):
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
navigateFallbackWhitelist: [/^(?!\/__).*/],
// Don't precache sourcemaps (they're large) and build asset manifest:
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// Perform type checking and linting in a separate process to speed up compilation
new ForkTsCheckerWebpackPlugin({
async: false,
tsconfig: paths.appTsConfig,
tslint: paths.appTsLint,
}),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
};
'use strict';
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const config = require('./webpack.config.dev');
const paths = require('./paths');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const host = process.env.HOST || '0.0.0.0';
module.exports = function(proxy, allowedHost) {
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebookincubator/create-react-app/issues/2271
// https://github.com/facebookincubator/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
disableHostCheck: !proxy ||
process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files won’t automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through Webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
// By default files from `contentBase` will not trigger a page reload.
watchContentBase: true,
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the Webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// It is important to tell WebpackDevServer to use the same "root" path
// as we specified in the config. In development, we always serve from /.
publicPath: config.output.publicPath,
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.plugin` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebookincubator/create-react-app/issues/293
// src/node_modules is not ignored to support absolute imports
// https://github.com/facebookincubator/create-react-app/issues/1065
watchOptions: {
ignored: ignoredFiles(paths.appSrc),
},
// Enable HTTPS if the HTTPS environment variable is set to 'true'
https: protocol === 'https',
host: host,
overlay: false,
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true,
},
public: allowedHost,
proxy,
before(app) {
// This lets us open files from the runtime error overlay.
app.use(errorOverlayMiddleware());
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432
app.use(noopServiceWorkerMiddleware());
},
};
};
declare module '*.svg'
declare module '*.png'
declare module '*.jpg'
{
"name": "front",
"version": "0.1.0",
"private": true,
"proxy": "http://0.0.0.0:7777",
"dependencies": {
"apollo-boost": "^0.1.4",
"apollo-cache-inmemory": "^1.2.1",
"apollo-link-context": "^1.0.8",
"apollo-link-http": "^1.5.4",
"apollo-upload-client": "^8.0.0",
"axios": "^0.18.0",
"graphql": "^0.13.2",
"material-ui": "^0.20.0",
"ramda": "^0.25.0",
"react": "^16.3.1",
"react-apollo": "^2.1.3",
"react-dom": "^16.3.1",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",
"redux": "^4.0.0",
"redux-actions": "^2.3.0",
"redux-logger": "^3.0.6",
"redux-observable": "^1.0.0-alpha.2",
"rxjs": "^6.1.0"
},
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js --env=jsdom"
},
"devDependencies": {
"@types/graphql": "^0.13.0",
"@types/jest": "^22.2.3",
"@types/material-ui": "^0.21.2",
"@types/node": "^9.6.5",
"@types/ramda": "^0.25.21",
"@types/react": "^16.3.10",
"@types/react-dom": "^16.0.5",
"@types/react-redux": "^5.0.19",
"@types/react-router-dom": "^4.2.6",
"@types/redux-actions": "^2.2.4",
"@types/redux-logger": "^3.0.6",
"async-each": "^1.0.1",
"autoprefixer": "7.1.6",
"babel-jest": "^22.1.0",
"babel-loader": "^7.1.2",
"babel-preset-react-app": "^3.1.1",
"case-sensitive-paths-webpack-plugin": "2.1.1",
"chalk": "1.1.3",
"css-loader": "0.28.7",
"dotenv": "4.0.0",
"dotenv-expand": "4.2.0",
"extract-text-webpack-plugin": "3.0.2",
"file-loader": "0.11.2",
"fork-ts-checker-webpack-plugin": "^0.2.8",
"fs-extra": "3.0.1",
"html-webpack-plugin": "2.29.0",
"jest": "22.1.4",
"node-sass": "^4.9.0",
"object-assign": "4.1.1",
"postcss-flexbugs-fixes": "3.2.0",
"postcss-loader": "2.0.8",
"promise": "8.0.1",
"raf": "3.4.0",
"react-dev-utils": "^5.0.1",
"resolve": "1.6.0",
"sass-loader": "^7.0.1",
"source-map-loader": "^0.2.1",
"style-loader": "0.19.0",
"styled-components": "^3.2.5",
"sw-precache-webpack-plugin": "0.11.4",
"ts-jest": "22.0.1",
"ts-loader": "^2.3.7",
"tsconfig-paths-webpack-plugin": "^2.0.0",
"tslint": "^5.7.0",
"tslint-config-prettier": "^1.10.0",
"tslint-react": "^3.2.0",
"typescript": "^2.8.1",
"uglifyjs-webpack-plugin": "^1.1.8",
"url-loader": "0.6.2",
"webpack": "3.8.1",
"webpack-dev-server": "2.9.4",
"webpack-manifest-plugin": "1.3.2",
"whatwg-fetch": "2.0.3"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.(j|t)s?(x)",
"<rootDir>/src/**/?(*.)(spec|test).(j|t)s?(x)"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.tsx?$": "<rootDir>/config/jest/typescriptTransform.js",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|ts|tsx)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.ts",
"ts",
"web.tsx",
"tsx",
"web.js",
"js",
"web.jsx",
"jsx",
"json",
"node",
"mjs"
],
"globals": {
"ts-jest": {
"tsConfigFile": "/home/merong/Project/money/front/tsconfig.test.json"
}
}
},
"babel": {
"presets": [
"react-app"
]
},
"eslintConfig": {
"extends": "react-app"
}
}
No preview for this file type
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild)
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrl;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
);
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
let compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, true));
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
return resolve({
stats,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`);
console.log();
}
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const jest = require('jest');
let argv = process.argv.slice(2);
// Watch unless on CI, in coverage mode, or explicitly running all tests
if (
!process.env.CI &&
argv.indexOf('--coverage') === -1 &&
argv.indexOf('--watchAll') === -1
) {
argv.push('--watch');
}
jest.run(argv);
import * as React from "react";
import { Switch, Route, Link } from "react-router-dom";
import Main from "components/gadgets/Main";
import Nav from "components/gadgets/Nav";
class App extends React.Component {
public render() {
return (
<div>
<Nav />
<Main />
</div>
);
}
}
export default App;
import Component from './Component'
export default Component
\ No newline at end of file
import * as React from "react";
import { Switch, Route } from "react-router-dom";
import RequestPage from "components/pages/RequestPage";
import DronePage from "components/pages/DronePage";
import HomePage from "components/pages/HomePage";
import RegisterPage from "components/pages/RegisterPage";
import MyPage from "components/pages/MyPage";
import ContractPage from "components/pages/ContractPage";
import LoginPage from "components/pages/LoginPage";
import OrgPage from "components/pages/OrgPage";
import BuyPage from "components/pages/BuyPage";
import DatasetPage from "components/pages/DatasetPage";
import SearchPage from "components/pages/SearchPage";
import JudgePage from "components/pages/JudgePage";
import { withRouter, RouteComponentProps } from "react-router-dom";
require("./styles.scss");
interface MyProps extends RouteComponentProps<{}> {}
class Main extends React.Component<MyProps> {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) window.scrollTo(0, 0);
}
public render() {
return (
<main className="Main">
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/request" component={RequestPage} />
<Route exact path="/drone" component={DronePage} />
<Route exact path="/register" component={RegisterPage} />
<Route exact path="/my-page" component={MyPage} />
<Route exact path="/contract/:id" component={ContractPage} />
<Route exact path="/org" component={OrgPage} />
<Route exact path="/buy" component={BuyPage} />
<Route exact path="/judge/:id" component={JudgePage} />
<Route exact path="/search/:id" component={SearchPage} />
<Route exact path="/dataset" component={DatasetPage} />
<Route exact path="/login" component={LoginPage} />
</Switch>
</main>
);
}
}
export default withRouter(Main);
.Main {
padding: 30px;
margin: 200px auto 0 auto;
width: 1280px;
}
\ No newline at end of file
import * as React from "react";
import { NavLink, Link } from "react-router-dom";
require("./styles.scss");
const activeStyle = {
textDecoration: "underline"
};
const Nav: React.SFC<{}> = () => (
<div className="nav">
<ul>
<li>
<NavLink exact to="/" activeStyle={activeStyle}>
<p>홈</p>
</NavLink>
</li>
<li>
<NavLink exact to="/my-page" activeStyle={activeStyle}>
<p>내페이지</p>
</NavLink>
</li>
</ul>
<ul>
<li>
<NavLink exact to="/drone" activeStyle={activeStyle}>
<p>드론등록</p>
</NavLink>
</li>
<li>
<NavLink exact to="/request" activeStyle={activeStyle}>
<p>허가신청</p>
</NavLink>
</li>
</ul>
<ul>
<li>
<NavLink exact to="/dataset" activeStyle={activeStyle}>
<p>데이터등록</p>
</NavLink>
</li>
<li>
<NavLink exact to="/buy" activeStyle={activeStyle}>
<p>데이터구매</p>
</NavLink>
</li>
</ul>
<ul>
<li>
<NavLink exact to="/login" activeStyle={activeStyle}>
<p>로그인</p>
</NavLink>
</li>
<li>
<NavLink exact to="/register" activeStyle={activeStyle}>
<p>가입</p>
</NavLink>
</li>
<li>
<button onClick={() => localStorage.clear()}>로그아웃</button>
</li>
</ul>
</div>
);
export default Nav;
.nav {
padding: 1rem;
z-index: 2;
position: fixed;
height: 3rem;
background-color: white;
top: 0;
left: 0;
right: 0;
ul {
margin: 0;
display: flex;
li {
margin-left: 10px;
}
}
}
import * as React from "react";
import { Link } from "react-router-dom";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
import DatePicker from "material-ui/DatePicker";
import Toggle from "material-ui/Toggle";
import MenuItem from "material-ui/MenuItem";
import DropDownMenu from "material-ui/DropDownMenu";
require("./styles.scss");
const style = {
width: "100%"
};
interface Props {
datasets: Array<any>;
buyDataset: Function;
}
class BuyPage extends React.Component<Props> {
public render() {
const { props } = this;
const { datasets, buyDataset } = props;
return (
<div className="buy-page">
<h2>데이터셋 구매</h2>
<ul>
{datasets.map(dataset => (
<li key={dataset.id}>
<h3>데이터</h3>
<p>{dataset.comment}</p>
<h3>촬영 기종</h3>
<p>{dataset.producer.model.name}</p>
<h3>소유자</h3>
<p>{dataset.producer.owner.email}</p>
<hr />
<RaisedButton
label="구매"
onClick={() => buyDataset(dataset.id)}
/>
</li>
))}
</ul>
</div>
);
}
}
export default BuyPage;
mutation buyDataset($id: ID!) {
dataset: buyDataset(id: $id) {
id
}
}
query FetchAllDatasets {
datasets: fetchAllDatasets {
id
comment
producer {
id
name
model {
id
name
}
owner {
id
email
}
}
}
}
import Component from "./Component";
import * as React from "react";
import { Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const FETCH_ALL_DATASETS = require("./fetchAllDatasets.gql");
const BUY_DATASET = require("./buyDataset.gql");
class FetchAllDatasetsQuery extends Query<{
datasets: any;
}> {}
class CreateContractMutation extends Mutation<{}> {}
const update = (history: any) => (cache, result) => history.push("/buy");
const QueryComponent: React.SFC<RouteComponentProps<{}>> = ({ history }) => (
<FetchAllDatasetsQuery query={FETCH_ALL_DATASETS} fetchPolicy="network-only">
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
else if (error) return <p>Error :(</p>;
else
return (
<CreateContractMutation
mutation={BUY_DATASET}
update={update(history)}
>
{mutate => {
const buyDataset = id => mutate({ variables: { id } });
return (
<Component datasets={data!.datasets} buyDataset={buyDataset} />
);
}}
</CreateContractMutation>
);
}}
</FetchAllDatasetsQuery>
);
export default QueryComponent;
.request-page {
width: 300px;
}
import * as React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
require("./styles.scss");
const style = {
width: "100%"
};
interface Props {
contract: any;
}
const statusLog = (status, review) => {
if (status === "wait") return "심사중";
else if (status === "ok") return "승인";
else return `반려사유: ${review}`;
};
class ContractPage extends React.Component<Props> {
public render() {
const { props } = this;
const { contract } = props;
return (
<div className="contract-page">
<h2>허가서</h2>
<h3>날짜</h3>
<p>{contract.date}</p>
<h3>지역</h3>
<p>{contract.area}</p>
<h3>상세주소</h3>
<p>{contract.address}</p>
<h3>사유</h3>
<p>{contract.reason}</p>
<h3>신청 상태</h3>
<p>{statusLog(contract.status, contract.review)}</p>
</div>
);
}
}
export default ContractPage;
query FetchContract($id: ID!) {
contract: fetchContract(id: $id) {
id
reason
date
area
address
status
review
}
}
import Component from "./Component";
import * as React from "react";
import { graphql, Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const FETCH_CONTRACT = require("./fetchContract.gql");
interface Props {
contract: any;
}
class FetchContractQuery extends Query<Props> {}
const QueryComponent: React.SFC<RouteComponentProps<{}>> = props => (
<FetchContractQuery
query={FETCH_CONTRACT}
fetchPolicy="network-only"
variables={{ id: props.match.params["id"] }}
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
else if (error || !data!.contract) return <p>Error :(</p>;
else return <Component contract={data!.contract} />;
}}
</FetchContractQuery>
);
export default withRouter(QueryComponent);
.register-page {
width: 300px;
}
\ No newline at end of file
import * as React from "react";
import { Link } from "react-router-dom";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
import DatePicker from "material-ui/DatePicker";
import Toggle from "material-ui/Toggle";
import MenuItem from "material-ui/MenuItem";
import DropDownMenu from "material-ui/DropDownMenu";
require("./styles.scss");
const style = {
width: "100%"
};
interface Props {
user: any;
createDataset(input: any): void;
}
interface State {
comment: string;
droneId: string;
}
class RequestPage extends React.Component<Props, State> {
state = {
comment: "",
droneId: ""
};
handleChangeComment = event => this.setState({ comment: event.target.value });
handleChangeDrone = (event, index, droneId) => this.setState({ droneId });
public render() {
const { props, state } = this;
const minDate = new Date();
const maxDate = new Date();
maxDate.setDate(maxDate.getDate() + 90);
const { createDataset } = props;
return (
<div className="dataset-page">
<h2>데이터셋 등록</h2>
<TextField
hintText="설명"
type="text"
value={state.comment}
onChange={this.handleChangeComment}
style={style}
/>
<h3>파일</h3>
<input type="file" />
<h3>촬영한 드론</h3>
<DropDownMenu
maxHeight={300}
value={state.droneId}
onChange={this.handleChangeDrone}
>
{props.user.drones.map(drone => (
<MenuItem
key={drone.id}
value={drone.id}
primaryText={`${drone.name} (${drone.model.name})`}
/>
))}
</DropDownMenu>
<RaisedButton
label="확인"
primary={true}
onClick={() => createDataset(state)}
/>
</div>
);
}
}
export default RequestPage;
mutation CreateDatase($input: DatasetInput!) {
dataset: createDataset(input: $input) {
id
}
}
query FetchCurrentUser {
user: fetchCurrentUser {
id
drones {
id
date
name
model {
id
name
}
owner {
id
email
}
}
}
}
import Component from "./Component";
import * as React from "react";
import { Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const FETCH_CURRENT_USER = require("./fetchCurrentUser.gql");
const CREATE_DATASET = require("./createDataset.gql");
class FetchCurrentUserQuery extends Query<{
user: any;
orgs: any;
}> {}
class CreateContractMutation extends Mutation<{}> {}
const update = (history: any) => (cache, result) => history.push("/my-page");
const QueryComponent: React.SFC<RouteComponentProps<{}>> = ({ history }) => (
<FetchCurrentUserQuery query={FETCH_CURRENT_USER} fetchPolicy="network-only">
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
else if (error) return <p>Error :(</p>;
else
return (
<CreateContractMutation
mutation={CREATE_DATASET}
update={update(history)}
>
{mutate => {
const createDataset = input => mutate({ variables: { input } });
return (
<Component user={data!.user} createDataset={createDataset} />
);
}}
</CreateContractMutation>
);
}}
</FetchCurrentUserQuery>
);
export default withRouter(QueryComponent);
import * as R from "ramda";
import * as React from "react";
import { Link } from "react-router-dom";
import DropDownMenu from "material-ui/DropDownMenu";
import MenuItem from "material-ui/MenuItem";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
require("./styles.scss");
interface State {
modelId: string;
name: string;
}
interface Props {
models: Array<any>;
registerDrone(input: any): void;
}
const style = {
width: "100%"
};
class DronePage extends React.Component<Props, State> {
state = {
modelId: "",
name: ""
};
handleChangeModel = (event, index, modelId) => this.setState({ modelId });
handleChangeName = event => this.setState({ name: event.target.value });
public render() {
const { props, state } = this;
return (
<div className="drone-page">
<h2>드론등록</h2>
<TextField
hintText="이름"
type="text"
value={state.name}
onChange={this.handleChangeName}
style={style}
/>
<h3>모델</h3>
<DropDownMenu
maxHeight={300}
value={state.modelId}
onChange={this.handleChangeModel}
>
{props.models.map(model => (
<MenuItem
key={model.id}
value={model.id}
primaryText={`${model.name}`}
/>
))}
</DropDownMenu>
<RaisedButton
label="등록하기"
primary={true}
style={style}
onClick={() => props.registerDrone(state)}
/>
</div>
);
}
}
export default DronePage;
query FetchAllModels {
models: fetchAllModels {
id
name
}
}
import Component from "./Component";
import * as React from "react";
import { Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const FETCH_ALL_MODELS = require("./fetchAllModels.gql");
const REGISTER_DRONE = require("./registerDrone.gql");
class FetchAllModelsQuery extends Query<{
models: Array<any>;
}> {}
class RegisterDroneMutation extends Mutation<{}> {}
const update = (history: any) => (cache, result) => history.push("/my-page");
const QueryComponent: React.SFC<RouteComponentProps<{}>> = ({ history }) => (
<FetchAllModelsQuery query={FETCH_ALL_MODELS}>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
else if (error) return <p>Error :(</p>;
else
return (
<RegisterDroneMutation
mutation={REGISTER_DRONE}
update={update(history)}
>
{mutate => {
const registerDrone = input => mutate({ variables: { input } });
return (
<Component
models={data!.models}
registerDrone={registerDrone}
/>
);
}}
</RegisterDroneMutation>
);
}}
</FetchAllModelsQuery>
);
export default withRouter(QueryComponent);
mutation RegisterDrone($input: DroneInput!) {
drone: registerDrone(input: $input) {
id
name
date
model {
id
name
}
}
}
\ No newline at end of file
.drone-page {
width: 300px;
}
\ No newline at end of file
import * as R from "ramda";
import * as React from "react";
require("./styles.scss");
class HomePage extends React.Component<{}> {
public render() {
const { props, state } = this;
return (
<div className="home-page">
<h1>1조 과제 시연</h1>
</div>
);
}
}
export default HomePage;
import * as React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
require("./styles.scss");
const style = {
// width: "100%"
};
interface Props {
org: any;
confirm: Function;
reject: Function;
}
class Tester extends React.Component<any> {
state = { review: "" };
handleChangeReview = event => this.setState({ review: event.target.value });
public render() {
const { props, state } = this;
const { id, confirm, reject } = props;
return (
<div>
<RaisedButton
label="승인"
primary={true}
style={style}
onClick={() => confirm(id, state.review)}
/>
<hr />
<TextField
hintText="사유"
type="text"
value={state.review}
onChange={this.handleChangeReview}
style={style}
/>
<RaisedButton
label="반려"
primary={true}
style={style}
onClick={() => reject(id, state.review)}
/>
</div>
);
}
}
class JudgePage extends React.Component<Props> {
public render() {
const { props, state } = this;
const { org } = props;
return (
<div className="judge-page">
<h2>신청서</h2>
<ul>
{org.contracts
.filter(contract => contract.status === "wait")
.map(contract => (
<li key={contract.id}>
<h3>사유</h3>
<p>{contract.reason}</p>
<h3>주소</h3>
<p>{contract.address}</p>
<h3>드론</h3>
<p>
{contract.drone.name}({contract.drone.model.name})
</p>
<Tester
id={contract.id}
confirm={props.confirm}
reject={props.reject}
/>
<br />
</li>
))}
</ul>
</div>
);
}
}
export default JudgePage;
query FetchOrg($id: ID!) {
org: fetchOrg(id: $id) {
id
name
contracts {
id
reason
address
status
drone {
id
name
model {
id
name
}
}
}
}
}
import Component from "./Component";
import * as React from "react";
import { graphql, Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const FETCH_ORG = require("./fetchOrg.gql");
const JUDGE_CONTRACT = require("./judgeContract.gql");
interface Props {
org: any;
}
class FetchContractQuery extends Query<Props> {}
class JudgeContractMutation extends Mutation<{}> {}
const update = (history: any) => (cache, result) => history.push('/org');
const QueryComponent: React.SFC<RouteComponentProps<{}> & Props> = props => (
<FetchContractQuery
query={FETCH_ORG}
fetchPolicy="network-only"
variables={{ id: props.match.params["id"] }}
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
else if (error || !data!.org) return <p>Error :(</p>;
else
return (
<JudgeContractMutation
mutation={JUDGE_CONTRACT}
update={update(history)}
>
{mutate => {
const confirm = (id, review) => {
mutate({ variables: { id, ok: true, review } });
props.history.push('/org');
}
const reject = (id, review) => {
mutate({ variables: { id, ok: false, review } });
props.history.push('/org');
}
return (
<Component org={data!.org} confirm={confirm} reject={reject} />
);
}}
</JudgeContractMutation>
);
}}
</FetchContractQuery>
);
export default withRouter(QueryComponent);
mutation JudgeContract($id: ID!, $ok: Boolean!, $review: String!) {
contract: judgeContract(id: $id, ok: $ok, review: $review) {
id
}
}
.register-page {
width: 300px;
}
\ No newline at end of file
import * as R from "ramda";
import * as React from "react";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
import { History } from "history";
require("./styles.scss");
interface Props {
login: (input) => void;
history: History;
}
const style = {
width: "100%"
};
class LoginPage extends React.Component<Props> {
state = {
// email: "",
// password: ""
email: "db@khu.ac.kr",
password: "db"
};
handleChangeEmail = event => this.setState({ email: event.target.value });
handleChangePassword = event =>
this.setState({ password: event.target.value });
public render() {
const { props, state } = this;
return (
<div className="login-page">
<form>
<h2>로그인</h2>
<TextField
hintText="email"
type="email"
value={state.email}
onChange={this.handleChangeEmail}
style={style}
/>
<TextField
hintText="password"
type="password"
value={state.password}
onChange={this.handleChangePassword}
style={style}
/>
<RaisedButton
label="로그인"
style={style}
onClick={() => props.login(state)}
/>
{/*
<RaisedButton
label="회원가입"
primary={true}
style={style}
onClick={() => props.history.push("register")}
/> */}
</form>
</div>
);
}
}
export default LoginPage;
import * as React from "react";
import Component from "./Component";
import { Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
import * as R from "ramda";
import { History } from "history";
const LOGIN = require("./login.gql");
class LoginMutation extends Mutation<{}> {}
interface Variables {
input: {
email: string;
password: string;
};
}
const update = (history: History) => (cache, { data }) => {
const { login } = data;
if (R.isNil(login)) {
alert("로그인 실패");
} else {
localStorage.setItem("token", login.token);
history.push("/");
}
};
const MutationComponent: React.SFC<RouteComponentProps<Variables>> = ({
match,
history
}) => (
<LoginMutation mutation={LOGIN} update={update(history)}>
{mutate => {
const login = input => mutate({ variables: { input } });
return <Component login={login} history={history} />;
}}
</LoginMutation>
);
export default withRouter(MutationComponent);
mutation Login($input: UserInput!) {
login: login(input: $input) {
user {
id
}
token
}
}
import * as React from "react";
import { Link } from "react-router-dom";
import { List, ListItem } from "material-ui/List";
import Avatar from "material-ui/Avatar";
require("./styles.scss");
interface Props {
user: any;
history: any;
}
class UserPage extends React.Component<Props> {
public render() {
const { user, history } = this.props;
console.log(this.props);
return (
<div className="my-page">
<h2>내 페이지</h2>
<h3>드론 목록</h3>
<List>
{user.drones.map(drone => (
<ListItem
key={drone.id}
primaryText={`${drone.name} (${drone.model.name})`}
leftAvatar={
<Avatar src={`/assets/img/${drone.model.name}.jpg`} />
}
/>
))}
</List>
<h3>허가서 목록</h3>
<List>
{user.contracts.map(contract => (
<ListItem
key={contract.id}
primaryText={`${contract.reason} (${contract.drone.name})`}
leftAvatar={
<Avatar src={`/assets/img/${contract.drone.model.name}.jpg`} />
}
onClick={() => history.push(`/contract/${contract.id}`)}
/>
))}
</List>
<h3>구매한 데이터셋</h3>
<ul>
{user.datasets.map(dataset => (
<li key={dataset.id}>
<h4>데이터</h4>
<p>{dataset.comment}</p>
<h4>촬영한 드론</h4>
<p>{dataset.producer.name}({dataset.producer.model.name})</p>
</li>
))}
</ul>
</div>
);
}
}
export default UserPage;
query FetchCurrentUser {
user: fetchCurrentUser {
id
drones {
id
name
date
model {
id
name
}
}
contracts {
id
reason
date
drone {
id
date
name
model {
id
name
}
}
}
datasets {
id
comment
producer {
id
name
model {
id
name
}
}
}
}
}
import * as React from "react";
import Component from "./Component";
import { graphql, Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const FETCH_CURRENT_USER = require("./fetchCurrentUser.gql");
interface Props {
user: any;
}
class FetchUserPageQuery extends Query<Props> {}
const QueryComponent: React.SFC<RouteComponentProps<{}>> = props => (
<FetchUserPageQuery
query={FETCH_CURRENT_USER} fetchPolicy="network-only">
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
else if (error || !data!.user) return <p>Error :(</p>;
else return <Component user={data!.user} history={props.history} />;
}}
</FetchUserPageQuery>
);
export default withRouter(QueryComponent);
.my-page {
width: 300px;
}
\ No newline at end of file
import * as React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
require("./styles.scss");
const style = {
width: "100%"
};
interface Props {
orgs: Array<any>;
}
class OrgPage extends React.Component<Props> {
public render() {
const { props } = this;
const { orgs } = props;
console.log(orgs, orgs.length);
return (
<div className="org-page">
<h2>신청서 심사</h2>
<ul>
{orgs.map(org => (
<li key={org.id}>
<h3>{org.name}</h3>
<p><Link to={`/judge/${org.id}`}>심사</Link></p>
<p><Link to={`/search/${org.id}`}>질의</Link></p>
</li>
))}
</ul>
</div>
);
}
}
export default OrgPage;
query FetchAllOrgs {
orgs: fetchAllOrgs {
id
name
}
}
import Component from "./Component";
import * as React from "react";
import { graphql, Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const FETCH_ALL_ORGS = require("./fetchAllOrgs.gql");
interface Props {
orgs: Array<any>;
}
class FetchContractQuery extends Query<Props> {}
const QueryComponent: React.SFC<RouteComponentProps<{}>> = props => (
<FetchContractQuery
query={FETCH_ALL_ORGS}
fetchPolicy="network-only"
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
else if (error || !data!.orgs) return <p>Error :(</p>;
else return <Component orgs={data!.orgs} />;
}}
</FetchContractQuery>
);
export default withRouter(QueryComponent);
.register-page {
width: 300px;
}
\ No newline at end of file
import * as React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
require("./styles.scss");
interface UserInput {
email: string;
password: string;
}
const style = {
width: "100%"
};
interface Props {
createUser: (input: UserInput) => void;
}
class RegisterPage extends React.Component<Props> {
state = {
password: "",
email: ""
};
handleChangeEmail = event => this.setState({ email: event.target.value });
handleChangePassword = event =>
this.setState({ password: event.target.value });
public render() {
const createUser = this.props.createUser;
const { props, state } = this;
return (
<div className="register-page">
<h2>가입하기</h2>
<TextField
hintText="email"
type="email"
value={state.email}
onChange={this.handleChangeEmail}
style={style}
/>
<TextField
hintText="password"
type="password"
value={state.password}
onChange={this.handleChangePassword}
style={style}
/>
<RaisedButton
label="확인"
primary={true}
style={style}
onClick={() => createUser(state)}
/>
</div>
);
}
}
export default RegisterPage;
mutation createUser($input: UserInput!) {
user: createUser(input: $input) {
id
email
}
}
import Component from "./Component";
import * as React from "react";
import { graphql, Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const CREATE_USER = require("./createUser.gql");
class CreateUserMutation extends Mutation<{}> {}
interface Variables {
id: string;
}
const update = (history: any) => (cache, result) => history.push('/');
const QueryComponent: React.SFC<RouteComponentProps<Variables>> = ({
match,
history
}) => (
<CreateUserMutation mutation={CREATE_USER} update={update(history)}>
{mutate => {
const createUser = input => mutate({ variables: { input } });
return <Component createUser={createUser} />;
}}
</CreateUserMutation>
);
export default withRouter(QueryComponent);
.register-page {
width: 300px;
}
\ No newline at end of file
import * as React from "react";
import { Link } from "react-router-dom";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
import DatePicker from "material-ui/DatePicker";
import Toggle from "material-ui/Toggle";
import MenuItem from "material-ui/MenuItem";
import DropDownMenu from "material-ui/DropDownMenu";
require("./styles.scss");
const style = {
width: "100%"
};
interface Props {
user: any;
orgs: any;
createContract(input: any): void;
}
interface State {
reason: string;
date: Date;
droneId: string;
area: string;
address: string;
}
class RequestPage extends React.Component<Props, State> {
state = {
reason: "",
date: new Date(),
droneId: "",
area: "지역",
address: ""
};
handleChangeReason = event => this.setState({ reason: event.target.value });
handleChangeDate = (event, date) => this.setState({ date });
handleChangeDrone = (event, index, droneId) => this.setState({ droneId });
handleChangeArea = (event, index, area) => this.setState({ area });
handleChangeAddress = event => this.setState({ address: event.target.value });
public render() {
const { props, state } = this;
const minDate = new Date();
const maxDate = new Date();
maxDate.setDate(maxDate.getDate() + 90);
return (
<div className="request-page">
<h2>허가 신청서 작성</h2>
<TextField
hintText="사유"
type="text"
value={state.reason}
onChange={this.handleChangeReason}
style={style}
/>
<DropDownMenu
maxHeight={300}
value={state.droneId}
onChange={this.handleChangeDrone}
>
{props.user.drones.map(drone => (
<MenuItem
key={drone.id}
value={drone.id}
primaryText={`${drone.name} (${drone.model.name})`}
/>
))}
</DropDownMenu>
<DatePicker
floatingLabelText="날짜"
onChange={this.handleChangeDate}
defaultDate={state.date}
minDate={minDate}
maxDate={maxDate}
/>
<DropDownMenu
maxHeight={300}
value={state.area}
onChange={this.handleChangeArea}
>
{props.orgs.map(org => (
<MenuItem key={org.id} value={org.name} primaryText={org.name} />
))}
</DropDownMenu>
<TextField
hintText="상세주소"
type="text"
value={state.address}
onChange={this.handleChangeAddress}
style={style}
/>
<RaisedButton
label="확인"
primary={true}
style={style}
onClick={() => props.createContract(state)}
/>
</div>
);
}
}
export default RequestPage;
mutation CreateContract($input: ContractInput!) {
contract: createContract(input: $input) {
id
}
}
query FetchCurrentUser {
user: fetchCurrentUser {
id
drones {
id
date
name
model {
id
name
}
}
}
orgs: fetchAllOrgs {
id
name
}
}
import Component from "./Component";
import * as React from "react";
import { Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const FETCH_CURRENT_USER = require("./fetchCurrentUser.gql");
const CREATE_CONTRACT = require("./createContract.gql");
class FetchCurrentUserQuery extends Query<{
user: any;
orgs: any;
}> {}
class CreateContractMutation extends Mutation<{}> {}
const update = (history: any) => (cache, result) => history.push("/my-page");
const QueryComponent: React.SFC<RouteComponentProps<{}>> = ({ history }) => (
<FetchCurrentUserQuery query={FETCH_CURRENT_USER} fetchPolicy="network-only">
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
else if (error) return <p>Error :(</p>;
else
return (
<CreateContractMutation
mutation={CREATE_CONTRACT}
update={update(history)}
>
{mutate => {
const createContract = input => mutate({ variables: { input } });
return (
<Component user={data!.user} orgs={data!.orgs} createContract={createContract} />
);
}}
</CreateContractMutation>
);
}}
</FetchCurrentUserQuery>
);
export default withRouter(QueryComponent);
import * as React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
require("./styles.scss");
const style = {
// width: "100%"
};
interface Props {
org: any;
}
class SearchPage extends React.Component<Props> {
public render() {
const { props, state } = this;
const { org } = props;
return (
<div className="judge-page">
<h2>신청서</h2>
<ul>
{org.contracts
.filter(contract => contract.status === "ok")
.map(contract => (
<li key={contract.id}>
<h3>사유</h3>
<p>{contract.reason}</p>
<h3>주소</h3>
<p>{contract.address}</p>
<h3>드론</h3>
<p>
{contract.drone.name}({contract.drone.model.name})
</p>
<br />
</li>
))}
</ul>
</div>
);
}
}
export default SearchPage;
query FetchOrg($id: ID!) {
org: fetchOrg(id: $id) {
id
name
contracts {
id
reason
address
status
drone {
id
name
model {
id
name
}
}
}
}
}
import Component from "./Component";
import * as React from "react";
import { graphql, Query, Mutation } from "react-apollo";
import { withRouter, RouteComponentProps } from "react-router";
const FETCH_ORG = require("./fetchOrg.gql");
interface Props {
org: any;
}
class FetchContractQuery extends Query<Props> {}
const update = (history: any) => (cache, result) => history.goBack();
const QueryComponent: React.SFC<RouteComponentProps<{}> & Props> = props => (
<FetchContractQuery
query={FETCH_ORG}
fetchPolicy="network-only"
variables={{ id: props.match.params["id"] }}
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
else if (error || !data!.org) return <p>Error :(</p>;
else return <Component org={data!.org} />;
}}
</FetchContractQuery>
);
export default withRouter(QueryComponent);
mutation JudgeContract($id: ID!, $ok: Boolean!, $review: String!) {
contract: judgeContract(id: $id, ok: $ok, review: $review) {
id
}
}
.register-page {
width: 300px;
}
\ No newline at end of file
import * as R from "ramda";
import { ApolloLink } from "apollo-link";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloClient } from "apollo-client";
import { createUploadLink } from "apollo-upload-client";
const authLink = setContext((req, { headers }) => {
const token = localStorage.getItem("token");
const authorization = token ? `Bearer ${token}` : "";
return { headers: R.merge(headers, { authorization }) };
});
const uploadLink = createUploadLink();
const link = ApolloLink.from([authLink, uploadLink]);
const cache = new InMemoryCache({
cacheRedirects: {
Query: {}
}
});
const client = new ApolloClient({ link, cache });
export default () => client;
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
ul {
padding: 0;
}
li {
list-style-type: none;
}
a {
color: #258fb8;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
\ No newline at end of file
import * as R from "ramda";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import { ApolloProvider } from "react-apollo";
import { Provider } from "react-redux";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import App from "components/App";
// import configureStore from "./configureStore";
import configureClient from "./configureClient";
import registerServiceWorker from "./registerServiceWorker";
import "./index.scss";
// const store = configureStore();
const client = configureClient();
const Root = () => (
<ApolloProvider client={client}>
<BrowserRouter>
<MuiThemeProvider>
<App />
</MuiThemeProvider>
</BrowserRouter>
</ApolloProvider>
);
ReactDOM.render(<Root />, document.getElementById("root") as HTMLElement);
registerServiceWorker();
import { combineReducers } from 'redux'
import { combineEpics } from 'redux-observable'
// tslint:disable:no-console
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the 'N+1' visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(
process.env.PUBLIC_URL!,
window.location.toString()
);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://goo.gl/SC7cgQ'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl: string) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker) {
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a 'New content is
// available; please refresh.' message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// 'Content is cached for offline use.' message.
console.log('Content is cached for offline use.');
}
}
};
}
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl: string) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type')!.indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
{
"compilerOptions": {
"outDir": "build/dist",
"module": "esnext",
"target": "es5",
"lib": [
"es6",
"dom",
"esnext.asynciterable"
],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": false,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": false,
"baseUrl": "./src"
},
"exclude": [
"../node_modules",
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts"
]
}
\ No newline at end of file
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs"
}
}
\ No newline at end of file
{
"extends": [],
"linterOptions": {
"exclude": [
"config/**/*.js",
"node_modules/**/*.ts"
]
}
}
\ No newline at end of file
nodejs 10.4.1
yarn 1.6.0
oracle DB // username: "system", password: "oracle", database: "khu"로 로그인 할 수 있어야 하고 테이블이 없어야함(두 번째 실행시 configureDB.ts synchronize를 false로 주지 않으면 에러발생)
front와 server에서 각각 yarn install을 입력해서 의존성을 받음
완료시 각각 yarn start로 개발서버를 띄울 수 있음
빌드가 잘 되지 않으면 node-sass, oracledb, typescript, babel, webpack을 yarn global add {패키지 이름}을 입력해서 전역으로 설치
server를 먼저 띄우고 front를 띄우면 front의 package.json의 proxy를 참조해서 server에 연결됨(이 부분에서 문제가 발생하면 화면은 나오지만 통신을 못함)
위와 같은 문제 발생시 front의 proxy를 localhost, 0.0.0.0, 진짜 IP등으로 바꿔가면서 실행
모든 과정이 준비되면
localhost:3000으로 접속해서 시연 가능
\ No newline at end of file
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
delete require.cache[require.resolve('./paths')];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}
var dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
`${paths.dotenv}.${NODE_ENV}`,
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
paths.dotenv,
].filter(Boolean);
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile,
})
);
}
});
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
NODE_ENV: process.env.NODE_ENV || 'development',
PUBLIC_URL: publicUrl,
}
);
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;
'use strict';
const path = require('path');
const fs = require('fs');
const url = require('url');
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
const envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return `${path}/`;
} else {
return path;
}
}
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
return ensureSlash(servedUrl, true);
}
module.exports = {
appPackageJson: resolveApp('package.json'),
appTsConfig: resolveApp('tsconfig.json'),
appTsLint: resolveApp('tslint.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveApp('src/setupTests.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
dotenv: resolveApp('.env'),
serverAssets: resolveApp('assets'),
appSrc: resolveApp('src'),
appLib: resolveApp('lib'),
appEntry: resolveApp('src/index.ts'),
appBuild: resolveApp('../build/server'),
temporalOutput: resolveApp('tmp'),
};
'use strict';
const webpack = require('webpack');
const paths = require('./paths');
const nodeExternals = require('webpack-node-externals');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
devtool: 'cheap-module-source-map',
target: 'node',
entry: paths.appEntry,
output: {
path: paths.temporalOutput,
filename: 'index.js'
},
externals: [nodeExternals()],
resolve: {
modules: [paths.appLib, paths.appSrc, paths.appNodeModules],
extensions: [
'.mjs',
'.web.ts',
'.ts',
'.web.tsx',
'.tsx',
'.web.js',
'.js',
'.json',
'.web.jsx',
'.jsx',
],
plugins: [
new TsconfigPathsPlugin({ configFile: paths.appTsConfig }),
],
},
module: {
strictExportPresence: true,
rules: [
{
test: /\.(js|jsx|mjs)$/,
loader: require.resolve('source-map-loader'),
enforce: 'pre',
include: paths.appSrc,
},
{
oneOf: [
{
test: /\.(js|jsx|mjs)$/,
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
},
},
{
test: /\.(ts|tsx)$/,
include: paths.appSrc,
use: [
{
loader: require.resolve('ts-loader'),
options: {
transpileOnly: true,
},
},
],
},
{
test: /\.(graphql|gql)$/,
loader: require.resolve('graphql-tag/loader'),
}
],
},
],
},
plugins: [
new webpack.BannerPlugin({ banner: 'require("source-map-support").install();', raw: true, entryOnly: false }),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"development"',
'__DEV__': true
}),
new ForkTsCheckerWebpackPlugin({
async: false,
watch: paths.appSrc,
tsconfig: paths.appTsConfig,
tslint: paths.appTsLint,
}),
new CopyWebpackPlugin([
{ from: paths.serverAssets, to: 'assets' },
])
],
devtool: 'sourcemap'
};
\ No newline at end of file
const webpack = require('webpack');
const paths = require('./paths');
const nodeExternals = require('webpack-node-externals');
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
target: 'node',
entry: paths.appEntry,
output: {
path: paths.appBuild,
filename: 'index.js'
},
externals: [nodeExternals()],
resolve: {
modules: [paths.appLib, paths.appSrc, paths.appNodeModules],
extensions: [
'.mjs',
'.web.ts',
'.ts',
'.web.tsx',
'.tsx',
'.web.js',
'.js',
'.json',
'.web.jsx',
'.jsx',
],
},
module: {
strictExportPresence: true,
rules: [
{
oneOf: [
{
test: /\.(js|jsx|mjs)$/,
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
},
},
{
test: /\.(ts|tsx)$/,
include: paths.appSrc,
use: [
{
loader: require.resolve('ts-loader'),
options: {
transpileOnly: true,
},
},
],
},
{
test: /\.(graphql|gql)$/,
loader: require.resolve('graphql-tag/loader'),
}
],
},
],
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"',
'__DEV__': false
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
comparisons: false,
},
mangle: {
safari10: true,
},
output: {
comments: false,
ascii_only: true,
},
}),
new CopyWebpackPlugin([
{ from: paths.serverAssets, to: 'assets' },
])
],
devtool: 'sourcemap'
};
\ No newline at end of file
{
"name": "server",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"post": "ts-node --project scripts/tsconfig.json scripts/post.ts",
"sync": "ts-node --project scripts/tsconfig.json scripts/sync.ts"
},
"devDependencies": {
"@types/compression": "^0.0.36",
"@types/express": "^4.11.1",
"@types/formidable": "^1.0.31",
"@types/fs-extra": "^5.0.2",
"@types/graphql": "^0.12.5",
"@types/morgan": "^1.7.35",
"@types/ramda": "^0.25.21",
"@types/redux-actions": "^2.2.4",
"@types/sequelize": "^4.27.10",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-0": "^6.24.1",
"chokidar": "^2.0.2",
"copy-webpack-plugin": "^4.5.1",
"fork-ts-checker-webpack-plugin": "^0.4.1",
"graphql-tag": "^2.7.3",
"nodemon": "^1.15.0",
"source-map-loader": "^0.2.3",
"source-map-support": "^0.5.3",
"start-server-webpack-plugin": "^2.2.5",
"ts-loader": "2.3.7",
"tsconfig-paths-webpack-plugin": "^3.0.2",
"tslint": "^5.9.1",
"typescript": "^2.7.2",
"webpack": "^3.11.0",
"webpack-node-externals": "^1.6.0"
},
"dependencies": {
"apollo-server-express": "^1.3.2",
"apollo-upload-server": "^5.0.0",
"body-parser": "^1.18.2",
"compression": "^1.7.2",
"express": "^4.16.2",
"formidable": "^1.2.1",
"fs-extra": "^5.0.0",
"graphql": "0.12",
"graphql-tools": "^2.21.0",
"helmet": "^3.11.0",
"jsonwebtoken": "^8.2.1",
"morgan": "^1.9.0",
"node-fetch": "^2.1.1",
"oracledb": "^2.3.0",
"ramda": "^0.25.0",
"serve-favicon": "^2.5.0",
"typeorm": "^0.1.16"
}
}
'use strict';
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
process.on('unhandledRejection', (err) => { throw err; });
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const fs = require('fs-extra');
fs.emptyDirSync(paths.appBuild);
const compiler = webpack(config);
compiler.run((err, stats) => { console.log(stats.compilation.errors) });
\ No newline at end of file
'use strict';
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
process.on('unhandledRejection', (err) => { throw err; });
const fs = require('fs-extra');
const webpack = require('webpack');
const nodemon = require('nodemon');
const config = require('../config/webpack.config.dev');
const paths = require('../config/paths');
const compiler = webpack(config);
fs.emptyDirSync(paths.temporalOutput);
const run = () => new Promise((res, rej) => {
compiler.watch({}, (err, stats) => {
if (err)
rej(err)
else
res(stats);
});
})
async function go() {
await run();
nodemon({
script: `${paths.temporalOutput}/index.js`,
ext: 'js json'
});
}
go();
\ No newline at end of file
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"lib": [
"es6",
"dom"
],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": false,
"baseUrl": "../",
"paths": {
"*": [
"node_modules/*",
"src/*",
"lib/*"
]
}
},
"exclude": [
"node_modules",
"tmp"
]
}
\ No newline at end of file
import { Application } from "express";
import { ConnectionOptions, createConnection } from "typeorm";
import Contract from "entity/Contract";
import Drone from "entity/Drone";
import Model from "entity/Model";
import Org from "entity/Org";
import User from "entity/User";
import Dataset from "entity/Dataset";
import fake from "../fake";
const options: ConnectionOptions = {
type: "oracle",
host: "localhost",
port: 1521,
username: "system",
password: "oracle",
database: "khu",
logger: "debug",
synchronize: true,
entities: [Contract, Drone, Model, Org, User, Dataset]
};
export default async (app: Application) => {
try {
const connection = await createConnection(options);
await fake(connection);
Object.assign(app.locals, { connection });
} catch (e) {
console.log(e);
}
};
import * as express from "express";
import { Application, RequestHandler } from "express";
import * as fs from "fs-extra";
import * as morgan from "morgan";
import * as helmet from "helmet";
import * as compression from "compression";
import graphql from "routers/graphql";
import graphiql from "routers/graphiql";
import configureDB from "./configureDB";
export default async (app: Application) => {
Object.assign(app.locals, { port: 7777 });
await configureDB(app);
app.use(morgan("dev"));
// app.use("/assets", express.static("assets"));
app.use("/graphql", graphql);
// app.use("/graphiql", graphiql);
app.listen(app.locals.port, () =>
console.log(`listening ${app.locals.port}`)
);
};
import {
Entity,
CreateDateColumn,
PrimaryGeneratedColumn,
Column,
ManyToMany,
ManyToOne,
EntityOptions,
OneToMany,
OneToOne
} from "typeorm";
import User from "./User";
import Drone from "./Drone";
import Org from "./Org";
@Entity("contracts")
export default class Contract {
@PrimaryGeneratedColumn() id: string;
@Column() reason: string;
@Column() date: string;
@Column() area: string;
@Column() address: string;
@Column() status: string;
@Column() review: string;
@ManyToOne(type => User)
writer: User;
@ManyToOne(type => Drone)
drone: Drone;
@ManyToOne(type => Org)
org: Org;
}
import {
Entity,
CreateDateColumn,
PrimaryGeneratedColumn,
Column,
ManyToMany,
ManyToOne,
EntityOptions,
OneToMany,
OneToOne
} from "typeorm";
import User from "./User";
import Drone from "./Drone";
import Org from "./Org";
@Entity("datasets")
export default class Dataset {
@PrimaryGeneratedColumn() id: string;
@Column() comment: string;
@ManyToOne(type => Drone)
producer: Drone;
@ManyToMany(type => User, user => user.datasets)
buyers: Array<User>;
}
import {
Entity,
CreateDateColumn,
PrimaryGeneratedColumn,
Column,
ManyToMany,
ManyToOne,
EntityOptions,
OneToMany,
OneToOne
} from "typeorm";
import User from "./User";
import Model from "./Model";
import Dataset from "./Dataset";
@Entity("drones")
export default class Drone {
@PrimaryGeneratedColumn() id: string;
@Column() date: string;
@Column() name: string;
@ManyToOne(type => User)
owner: User;
@ManyToOne(type => Model)
model: Model;
@OneToMany(type => Dataset, dataset => dataset.producer)
datasets: Dataset;
}
import {
Entity,
CreateDateColumn,
PrimaryGeneratedColumn,
Column,
ManyToMany,
ManyToOne,
EntityOptions,
OneToMany,
OneToOne
} from "typeorm";
import Drone from "./Drone";
@Entity("models")
export default class Model {
@PrimaryGeneratedColumn() id: string;
@Column() name: string;
}
import {
Entity,
CreateDateColumn,
PrimaryGeneratedColumn,
Column,
ManyToMany,
ManyToOne,
EntityOptions,
OneToMany,
OneToOne
} from "typeorm";
import Contract from "./Contract";
@Entity("orgs")
export default class Org {
@PrimaryGeneratedColumn()
id: string;
@Column()
name: string;
@OneToMany(type => Contract, contract => contract.org)
contracts: Array<Contract>;
}
import {
Entity,
CreateDateColumn,
PrimaryGeneratedColumn,
Column,
ManyToMany,
JoinTable,
ManyToOne,
EntityOptions,
OneToMany,
OneToOne
} from "typeorm";
import Dataset from "./Dataset";
import Drone from "./Drone";
import Contract from "./Contract";
@Entity("users")
export default class User {
@PrimaryGeneratedColumn() id: string;
@Column() email: string;
@Column() password: string;
@OneToMany(type => Drone, drone => drone.owner)
drones: Array<Drone>;
@OneToMany(type => Contract, contract => contract.writer)
contracts: Array<Contract>;
@ManyToMany(type => Dataset, dataset => dataset.buyers)
@JoinTable()
datasets: Array<Dataset>;
}
import { Connection } from "typeorm";
import User from "entity/User";
import Org from "entity/Org";
import Model from "entity/Model";
export default async function fake(connection: Connection) {
const userRepo = connection.getRepository(User);
const result = await userRepo.find();
console.log(result);
if (result.length > 0) {
console.log("NOT FIRST.. END FAKE");
return;
}
try {
console.log("FIRST.. FAKE START");
let user = new User();
user.email = "db@khu.ac.kr";
user.password = "db";
await userRepo.save(user);
console.log("USER DONE");
let modelA = new Model();
modelA.name = "F15";
let modelB = new Model();
modelB.name = "F20";
let modelC = new Model();
modelC.name = "Raptor";
let modelD = new Model();
modelD.name = "F22";
let modelE = new Model();
modelE.name = "Valkyrie";
let modelF = new Model();
modelF.name = "Battlecruiser";
console.log("MODEL READY");
await connection
.createQueryBuilder()
.insert()
.into(Model)
.values([modelA, modelB, modelC, modelD, modelE, modelF])
.execute();
console.log("MODEL DONE");
let OrgA = new Org();
OrgA.name = "서울";
let OrgB = new Org();
OrgB.name = "수원";
let OrgC = new Org();
OrgC.name = "부산";
let OrgD = new Org();
OrgD.name = "춘천";
console.log("ORG READY");
await connection
.createQueryBuilder()
.insert()
.into(Org)
.values([OrgA, OrgB, OrgC, OrgD])
.execute();
console.log("ORG DONE");
console.log("FAKE OVER");
} catch (e) {
console.log(e, "FAKE ERROR");
}
}
File mode changed
import 'reflect-metadata';
import * as express from 'express';
import configureApp from './configureApp';
const app = express();
configureApp(app);
\ No newline at end of file
import * as express from 'express';
import { graphiqlExpress } from 'apollo-server-express';
const router = express.Router();
router.get('/', graphiqlExpress({ endpointURL: '/graphql' }));
export default router;
import * as R from "ramda";
import { Context } from "../";
import Contract from "entity/Contract";
import Drone from "entity/Drone";
import Dataset from "entity/Dataset";
import User from "entity/User";
import Org from "entity/Org";
export default async (root: {}, { id }, context: Context) => {
const { connection, session } = context;
console.log("AAA");
const userRepo = connection.getRepository(User);
const datasetRepo = connection.getRepository(Dataset);
const user = await userRepo.findOneById(session.id);
const datasets = await userRepo
.createQueryBuilder()
.relation(User, "datasets")
.of(user)
.loadMany();
const dataset = await datasetRepo.findOneById(id);
console.log(user);
user!.datasets = [...datasets, dataset];
try {
const result = await userRepo.save(user!);
console.log("UPDATE", result);
} catch (err) {
console.log(err, 11111);
}
return dataset;
};
import * as R from "ramda";
import { Context } from "../";
import Contract from "entity/Contract";
import Drone from "entity/Drone";
import User from "entity/User";
import Org from "entity/Org";
export default async (
root: {},
{ input: { reason, date, droneId, area, address } },
context: Context
) => {
const { connection } = context;
const contractRepo = connection.getRepository(Contract);
const droneRepo = connection.getRepository(Drone);
const userRepo = connection.getRepository(User);
const orgRepo = connection.getRepository(Org);
const userId = context.session.id;
const user = await userRepo.findOneById(userId);
if (R.isNil(user)) throw new Error("Session Error");
const drone = await droneRepo.findOneById(droneId);
if (R.isNil(drone)) throw new Error("Invalid Drone ID");
const org = await orgRepo.findOne({ where: { name: area } });
let contract = new Contract();
contract.reason = reason;
contract.date = date;
contract.area = area;
contract.address = address;
contract.drone = drone;
contract.status = "wait";
contract.review = "심사중";
contract.writer = user!;
contract.org = org!;
await contractRepo.save(contract);
return contract;
};
import * as R from "ramda";
import { Context } from "../";
import Contract from "entity/Contract";
import Drone from "entity/Drone";
import Dataset from "entity/Dataset";
import User from "entity/User";
import Org from "entity/Org";
export default async (
root: {},
{ input: { comment, droneId } },
context: Context
) => {
const { connection } = context;
const datasetRepo = connection.getRepository(Dataset);
const droneRepo = connection.getRepository(Drone);
const drone = await droneRepo.findOneById(droneId);
let dataset = new Dataset();
dataset.comment = comment;
dataset.producer = drone!;
await datasetRepo.save(dataset);
return dataset;
};
import { Context } from "../";
import User from "entity/User";
export default async (
root: {},
{ input: { email, password } },
context: Context
) => {
const { connection } = context;
const userRepo = connection.getRepository(User);
let user = new User();
user.email = email;
user.password = password;
await userRepo.save(user);
return user;
};
import buyDataset from "./buyDataset";
import createUser from "./createUser";
import createContract from "./createContract";
import createDataset from "./createDataset";
import login from "./login";
import registerDrone from "./registerDrone";
import judgeContract from "./judgeContract";
export default {
buyDataset,
createContract,
createUser,
createDataset,
judgeContract,
login,
registerDrone
};
import * as R from "ramda";
import { Context } from "../";
import Contract from "entity/Contract";
import Drone from "entity/Drone";
import User from "entity/User";
import Org from "entity/Org";
export default async (root: {}, { id, ok, review }, context: Context) => {
const { connection } = context;
const contractRepo = connection.getRepository(Contract);
const result = await contractRepo
.createQueryBuilder()
.update(Contract)
.set({ status: ok ? "ok" : "rejected", review })
.where("id = :id", { id })
.execute();
return null;
};
import { Context } from "../";
import User from "entity/User";
import * as R from "ramda";
// password를 암호화하자
export default async (
root: {},
{ input: { email, password } },
context: Context
) => {
const { connection } = context;
const userRepo = connection.getRepository(User);
const user = await userRepo.findOne({
where: {
email,
password
}
});
if (R.isNil(user)) return null;
const token = user!.id;
return { user, token };
};
import * as R from "ramda";
import { Context } from "../";
import Drone from "entity/Drone";
import Model from "entity/Model";
import User from "entity/User";
export default async (root: {}, { input: { modelId, name } }, context: Context) => {
const { connection, session } = context;
const droneRepo = connection.getRepository(Drone);
const modelRepo = connection.getRepository(Model);
const userRepo = connection.getRepository(User);
const userId = session.id;
const user = await userRepo.findOneById(userId);
if (R.isNil(user)) throw new Error("Session Error");
const model = await modelRepo.findOneById(modelId);
if (R.isNil(model)) throw new Error("Invalid Drone Model");
let drone = new Drone();
drone.name = name;
drone.date = new Date().toString();
drone.owner = user!;
drone.model = model;
await droneRepo.save(drone);
console.log(drone);
return drone;
};
import { Context } from "../";
import Dataset from "entity/Dataset";
export default async (root: {}, { id }, context: Context) => {
const { connection } = context;
const datasetRepo = connection.getRepository(Dataset);
const datasets = await datasetRepo.find();
console.log(datasets);
return datasets;
};
import { Context } from "../";
import Model from "entity/Model";
export default async (root: {}, { id }, context: Context) => {
const { connection } = context;
const modelRepo = connection.getRepository(Model);
const models = await modelRepo.find();
return models;
};
import { Context } from "../";
import Org from "entity/Org";
export default async (root: {}, { id }, context: Context) => {
const { connection } = context;
const orgRepo = connection.getRepository(Org);
const orgs = await orgRepo.find();
return orgs;
};
import { Context } from "../";
import Contract from "entity/Contract";
export default async (root: {}, { id }, context: Context) => {
const { connection } = context;
const contractRepo = connection.getRepository(Contract);
const contract = await contractRepo.findOneById(id);
return contract;
};
import { Context } from "../";
import User from "entity/User";
export default async (root: {}, {}, context: Context) => {
const { connection, session } = context;
const userRepo = connection.getRepository(User);
const userId = session.id;
const user = await userRepo.findOneById(userId);
console.log(user);
return user;
};
import { Context } from "../";
import Org from "entity/Org";
export default async (root: {}, { id }, context: Context) => {
const { connection } = context;
const orgRepo = connection.getRepository(Org);
const org = await orgRepo.findOneById(id);
return org;
};
import { Context } from "../";
import User from "entity/User";
export default async (root: {}, { id }, context: Context) => {
const { connection } = context;
const userRepo = connection.getRepository(User);
const user = await userRepo.findOneById(id);
return user;
};
import fetchAllModels from "./fetchAllModels";
import fetchAllDatasets from "./fetchAllDatasets";
import fetchAllOrgs from "./fetchAllOrgs";
import fetchUser from "./fetchUser";
import fetchContract from "./fetchContract";
import fetchCurrentUser from "./fetchCurrentUser";
import fetchOrg from "./fetchOrg";
export default {
fetchAllModels,
fetchAllDatasets,
fetchAllOrgs,
fetchUser,
fetchOrg,
fetchContract,
fetchCurrentUser
};
import * as R from "ramda";
import { Context } from "../";
import Contract from "entity/Contract";
export default {
async drone(contract, {}, context: Context) {
if (contract.drone) return contract.drone;
const contractRepo = context.connection.getRepository(Contract);
const model = await contractRepo
.createQueryBuilder()
.relation(Contract, "drone")
.of(contract)
.loadOne();
return model;
}
};
import * as R from "ramda";
import { Context } from "../";
import Dataset from "entity/Dataset";
export default {
async producer(dataset, {}, context: Context) {
if (dataset.producer) return dataset.producer;
const datasetRepo = context.connection.getRepository(Dataset);
const producer = await datasetRepo
.createQueryBuilder()
.relation(Dataset, "producer")
.of(dataset)
.loadOne();
return producer;
}
};
import * as R from "ramda";
import { Context } from "../";
import Drone from "entity/Drone";
export default {
async model(drone, {}, context: Context) {
if (drone.model) return drone.model;
const droneRepo = context.connection.getRepository(Drone);
const model = await droneRepo
.createQueryBuilder()
.relation(Drone, "model")
.of(drone)
.loadOne();
return model;
},
async owner(drone, {}, context: Context) {
if (drone.owner) return drone.owner;
const droneRepo = context.connection.getRepository(Drone);
const owner = await droneRepo
.createQueryBuilder()
.relation(Drone, "owner")
.of(drone)
.loadOne();
return owner;
}
};
import * as R from "ramda";
import { Context } from "../";
export default {};
import * as R from "ramda";
import { Context } from "../";
import Org from "entity/Org";
export default {
async contracts(org, {}, context: Context) {
if (org.contracts) return org.model;
const orgRepo = context.connection.getRepository(Org);
const contracts = await orgRepo
.createQueryBuilder()
.relation(Org, "contracts")
.of(org)
.loadOne();
console.log("Hello", contracts);
return contracts;
}
};
import * as R from "ramda";
import { Context } from "../";
import User from "entity/User";
export default {
async drones(user, {}, context: Context) {
const userRepo = context.connection.getRepository(User);
const drones = await userRepo
.createQueryBuilder()
.relation(User, "drones")
.of(user)
.loadMany();
return drones;
},
async contracts(user, {}, context: Context) {
const userRepo = context.connection.getRepository(User);
const contracts = await userRepo
.createQueryBuilder()
.relation(User, "contracts")
.of(user)
.loadMany();
return contracts;
},
async datasets(user, {}, context: Context) {
const userRepo = context.connection.getRepository(User);
const datasets = await userRepo
.createQueryBuilder()
.relation(User, "datasets")
.of(user)
.loadMany();
return datasets;
}
};
import Contract from "./Contract";
import Drone from "./Drone";
import Dataset from "./Dataset";
import Model from "./Model";
import Org from "./Org";
import User from "./User";
export default { Contract, Drone, Dataset, Model, Org, User };
import * as express from "express";
import { graphqlExpress } from "apollo-server-express";
import * as R from "ramda";
import * as jwt from "jsonwebtoken";
import * as bodyParser from "body-parser";
import schema from "./schema";
import { Connection } from "typeorm";
const { apolloUploadExpress } = require("apollo-upload-server");
const router = express.Router();
const formatError = R.always("GraphQL Error"); // OFF NOW
const extractSession = req =>
req.headers["authorization"]
? req.headers["authorization"].split(" ")[1]
: null;
export interface Context {
connection: Connection;
session: {
id: string;
};
}
router.use(
"/",
bodyParser.json(),
apolloUploadExpress(),
graphqlExpress(async (req, res) => {
const connection = req!.app.locals.connection;
const session = { id: extractSession(req) };
console.log(session);
const context: Context = { connection, session };
return { schema, context };
})
);
export default router;
import { makeExecutableSchema } from "graphql-tools";
import Query from "./Query";
import Mutation from "./Mutation";
import Types from "./Types";
const typeDefs = require("./typeDefs.gql");
const { GraphQLUpload: Upload } = require("apollo-upload-server");
const resolvers = {
Query,
Mutation,
...Types
};
export default makeExecutableSchema({ typeDefs, resolvers });
type Contract {
id: ID!
reason: String!
date: String!
address: String!
area: String!
status: String!
review: String!
writer: User!
drone: Drone!
}
type Drone {
id: ID!
name: String!
date: String!
model: Model!
datasets: [Dataset!]!
owner: User!
}
type Dataset {
id: ID!
comment: String!
producer: Drone!
}
type Model {
id: ID!
name: String!
}
type Org {
id: ID!
name: String!
contracts: [Contract!]!
}
type User {
id: ID!
email: String!
password: String!
contracts: [Contract!]!
drones: [Drone!]!
datasets: [Dataset!]!
}
type Query {
fetchAllModels: [Model!]!
fetchAllDatasets: [Dataset!]!
fetchAllOrgs: [Org!]!
fetchCurrentUser: User
fetchOrg(id: ID!): Org
fetchUser(id: ID!): User
fetchContract(id: ID!): Contract
}
type Mutation {
buyDataset(id: ID!): Dataset
createContract(input: ContractInput!): Contract
createUser(input: UserInput!): User
createDataset(input: DatasetInput!): Dataset
login(input: UserInput!): LoginResult
registerDrone(input: DroneInput!): Drone
judgeContract(id: ID!, ok: Boolean!, review: String!): Contract
}
input ContractInput {
droneId: ID!
reason: String!
date: String!
address: String!
area: String!
}
input DroneInput {
modelId: ID!
name: String!
}
input DatasetInput {
droneId: ID!
comment: String!
}
type LoginResult {
user: User!
token: String!
}
input UserInput {
email: String!
password: String!
}
type Schema {
query: Query
mutation: Mutation
}
{
"compilerOptions": {
"outDir": "../build/server",
"module": "es2015",
"target": "es5",
"lib": [
"es6",
"dom"
],
"sourceMap": true,
"allowJs": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": false,
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/*",
"lib/*"
]
}
},
"exclude": [
"node_modules",
"tmp"
]
}
\ No newline at end of file
{
"rules": {
"align": [
false,
"parameters",
"arguments",
"statements"
],
"ban": false,
"class-name": false,
"comment-format": [
false,
"check-space"
],
"curly": false,
"eofline": false,
"forin": false,
"indent": [ false, "spaces" ],
"interface-name": [false, "never-prefix"],
"jsdoc-format": false,
"jsx-no-lambda": false,
"jsx-no-multiline-js": false,
"label-position": false,
"max-line-length": [ false, 120 ],
"member-ordering": [
false,
"public-before-private",
"static-before-instance",
"variables-before-functions"
],
"no-any": false,
"no-arg": false,
"no-bitwise": false,
"no-console": [
false,
"log",
"error",
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-debugger": false,
"no-duplicate-variable": false,
"no-empty": false,
"no-eval": false,
"no-shadowed-variable": false,
"no-string-literal": false,
"no-switch-case-fall-through": false,
"no-trailing-whitespace": false,
"no-unused-expression": false,
"no-use-before-declare": false,
"one-line": [
false,
"check-catch",
"check-else",
"check-open-brace",
"check-whitespace"
],
"quotemark": [false, "single", "jsx-double"],
"radix": false,
"semicolon": [false, "always"],
"switch-default": false,
"trailing-comma": [false],
"triple-equals": [ false, "allow-null-check" ],
"typedef": [
false,
"parameter",
"property-declaration"
],
"typedef-whitespace": [
false,
{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}
],
"variable-name": [false, "ban-keywords", "check-format", "allow-leading-underscore", "allow-pascal-case"],
"whitespace": [
false,
"check-branch",
"check-decl",
"check-module",
"check-operator",
"check-separator",
"check-type",
"check-typecast"
]
}
}