Initial Commit

This commit is contained in:
Jose 2020-08-22 15:35:42 -05:00
commit 1f37d91e8e
9 changed files with 3725 additions and 0 deletions

8
.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
node_modules
semantic/src
semantic/tasks
.idea/
.env
dist/.DS_Store
**/.DS_Store
dist/

45
gulpfile.js Normal file
View file

@ -0,0 +1,45 @@
const { dest, src, task, watch } = require('gulp');
const { createProject } = require('gulp-typescript');
const tsconf = createProject('tsconfig.json');
/**
* @param {String} dir
*/
const copy = (dir) => {
return src([`${dir}/**/*`]).pipe(dest(dir.replace('src', 'dist')));
};
const build = () => {
return src('src/**/*.ts').pipe(tsconf()).js.pipe(dest('dist'));
};
task('build', () => {
copy('src/static');
copy('src/app/Views');
return build();
});
task('copy', () => {
copy('src/static');
return copy('src/app/Views');
});
task('default', () => {
let space = String();
for (let _ = 0; _ < process.stdout.columns; _++) {
space += "-";
}
console.log(space);
console.error("No default task has been created");
console.log(space);
});
task('watch', () => {
return watch(['src/static/**/*', 'src/app/Views/**/*'], () => {
copy('src/static');
return copy('src/app/Views');
});
});

3417
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

30
package.json Normal file
View file

@ -0,0 +1,30 @@
{
"name": "img_paste",
"version": "1.0.0",
"description": "",
"main": "./dist/app.js",
"scripts": {
"serve-debug": "nodemon --inspect dist/app.js",
"watch-ts": "tsc -w",
"debug": "npm run build && npm run watch-debug",
"build": "gulp build"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/body-parser": "^1.19.0",
"@types/express": "^4.17.7",
"@types/mongoose": "^5.7.31",
"@types/multer": "^1.4.4",
"@types/shortid": "0.0.29",
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"gulp": "^4.0.2",
"gulp-typescript": "^6.0.0-alpha.1",
"mongoose": "^5.9.23",
"multer": "^1.4.2",
"shortid": "^2.2.15",
"typescript": "^3.9.6"
}
}

53
src/app.ts Normal file
View file

@ -0,0 +1,53 @@
import { json, urlencoded } from 'body-parser'
import { config } from 'dotenv'
import express, { Application } from 'express'
import { existsSync, mkdirSync } from 'fs'
import mongoose from 'mongoose'
import multer from 'multer'
import path from 'path'
import * as routes from './app/routes'
config()
const init = async () => {
const app = express()
app.use(json())
app.use(urlencoded({
extended: true
}))
await mongoose.connect(`mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@${process.env.MONGO_URI}/Images?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
const uploadPath = path.join(__dirname, './app/Uploads')
if (!existsSync(uploadPath)) {
mkdirSync(uploadPath)
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadPath)
},
filename: (req, file, cb) => {
cb(null, `${file.fieldname}-${Date.now()}`)
}
})
const uploader = multer({ storage })
routes.use(app, uploader)
return app
}
init().then((app: Application) => {
app.listen(process.env.PORT, () => {
console.log(`Listening on http://localhost:${process.env.PORT}`)
})
}).catch((err) => {
console.error(err)
process.exit(-1)
})

View file

@ -0,0 +1,19 @@
import { Document, model, Schema } from 'mongoose'
import shortid from 'shortid'
const ImgSchema = new Schema({
_id: {
type: String,
default: shortid.generate
},
data: Buffer,
contentType: String
})
export type ImgType = Document & {
_id: string,
data: Buffer,
contentType: string
}
export default model<ImgType>("Images", ImgSchema, "Images")

50
src/app/Views/upload.html Normal file
View file

@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ImageBin</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"
integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
<style>
.form-file * {
cursor: pointer;
}
</style>
</head>
<body>
<div class="container d-flex flex-column justify-content-center"
style="width: 98vw; height: 90vh; max-width: 768px; max-height: 90vh">
<div class="d-block text-center header">
<h2>
oitsjustjose's Image Bin
</h2>
</div>
<form method="POST" enctype="multipart/form-data">
<div class="form-file mb-3">
<input type="file" class="form-file-input" id="image" name="image" accept="image/*" required>
<label class="form-file-label" for="image">
<span class="form-file-text">Upload an image...</span>
<span class="form-file-button">Browse</span>
</label>
</div>
<button type="submit" class="btn btn-primary d-block m-auto" disabled>Upload!</button>
</form>
</div>
<script>
const form = document.forms[0];
form.addEventListener('change', (evt) => {
const filename = evt.target.files[0].name;
form.querySelector('.form-file-text').innerText = filename;
form.querySelector('.btn[type=submit]').removeAttribute('disabled')
})
</script>
</body>
</html>

34
src/app/routes.ts Normal file
View file

@ -0,0 +1,34 @@
import { Application } from 'express'
import Image from './Models/img.model'
import { Multer } from 'multer'
import fs from 'fs'
import path from 'path'
export const use = (app: Application, uploader: Multer) => {
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "./Views/upload.html"))
})
app.get("/:slug", async (req, res) => {
const img = await Image.findById(req.params.slug)
if (img) {
res.contentType(img.contentType)
res.send(img.data)
} else {
res.status(404).end()
}
})
app.post("/", uploader.single('image'), async (req, res) => {
const fp = path.join(__dirname + '/Uploads/' + req.file.filename)
const img = new Image({
data: fs.readFileSync(fp),
contentType: req.file.mimetype
})
await img.save()
res.redirect(`/${img._id}`)
// fs.unlinkSync(fp)
})
}

69
tsconfig.json Normal file
View file

@ -0,0 +1,69 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}