├── .gitignore ├── README.md ├── package.json ├── src ├── app.ts ├── controllers │ └── file.controllers.ts ├── database.ts ├── index.ts ├── libs │ └── multer.ts ├── models │ └── File.ts └── routes │ └── index.ts ├── tsconfig.json └── uploads └── b6f9d702-ceec-4182-9b0f-54c4edc672de.png /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.log 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | dist 7 | .env 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # API REST (typescript) 2 | ## Description 3 | 4 | This repository is a Application software with NODEjs, Express, MongoDB,etc this application contains an API created with TYPESCRIPT. 5 | 6 | ## Installation 7 | Using Typescript, Express, Mongoose, Multer,etc preferably. 8 | 9 | ## DataBase 10 | Using MongoDB preferably. 11 | 12 | ## Apps 13 | Using Postman, Insomnia,etc to feed the api. 14 | 15 | ## Usage 16 | ```html 17 | $ git clone https://github.com/DanielArturoAlejoAlvarez/api-rest-typescript-uploads.git [NAME APP] 18 | 19 | $ npm install 20 | 21 | $ npm run dev 22 | ``` 23 | Follow the following steps and you're good to go! Important: 24 | 25 | 26 | ![alt text](https://media1.giphy.com/media/RF5mb1srv4ALu/source.gif) 27 | 28 | 29 | ## Coding 30 | 31 | ### Routes 32 | 33 | ```typescript 34 | ... 35 | import {Router} from "express"; 36 | 37 | import {getFiles, getFileById, saveFile, updateFile, deleteFile} from "../controllers/file.controllers"; 38 | 39 | import upload from '../libs/multer'; 40 | 41 | const router = Router(); 42 | 43 | router.route('/files') 44 | .post(upload.single('image'), saveFile) 45 | .get(getFiles); 46 | 47 | router.route('/files/:id') 48 | .get(getFileById) 49 | .delete(deleteFile) 50 | .put(updateFile) 51 | 52 | export default router; 53 | ... 54 | ``` 55 | 56 | ### Server 57 | 58 | ```typescript 59 | ... 60 | import {connect} from "mongoose"; 61 | 62 | export async function Connection() { 63 | await connect("mongodb://127.0.0.1:27017/[your database]", { 64 | useNewUrlParser: true, 65 | useUnifiedTopology: true, 66 | useCreateIndex: true, 67 | useFindAndModify: false 68 | }); 69 | 70 | console.log("DB connect!"); 71 | } 72 | ... 73 | ``` 74 | 75 | ### Controllers 76 | 77 | 78 | ```typescript 79 | ... 80 | export const saveFile = async (req:Request, res: Response): Promise => { 81 | 82 | console.log(req.body); 83 | 84 | console.log(req.file); 85 | 86 | const {displayName,description,status} = req.body; 87 | 88 | const newFile = new File({ 89 | displayName, 90 | description, 91 | status 92 | }); 93 | 94 | newFile.url = req.file.path; 95 | 96 | await newFile.save(); 97 | 98 | return res.json({ 99 | msg: "File saved successfully!", 100 | newFile 101 | }); 102 | } 103 | ... 104 | 105 | ``` 106 | 107 | ### Model 108 | 109 | ```typescript 110 | ... 111 | import {Schema,model,Document} from "mongoose"; 112 | 113 | interface IFile extends Document{ 114 | displayName: string; 115 | description: string; 116 | url: string; 117 | status: boolean; 118 | } 119 | 120 | const FileSchema = new Schema({ 121 | displayName: { 122 | type: String, 123 | required: true 124 | }, 125 | description: { 126 | type: String, 127 | required: false 128 | }, 129 | url: { 130 | type: String, 131 | required: true, 132 | max: 512 133 | }, 134 | dateReg: { 135 | type: Date, 136 | default: Date.now() 137 | }, 138 | status: { 139 | type: String, 140 | default: 'ACTIVE' 141 | } 142 | }); 143 | 144 | export default model('File', FileSchema); 145 | ... 146 | ``` 147 | 148 | 149 | 150 | ## Contributing 151 | 152 | Bug reports and pull requests are welcome on GitHub at https://github.com/DanielArturoAlejoAlvarez/api-rest-typescript-uploads. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. 153 | 154 | 155 | ## License 156 | 157 | The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). 158 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-rest-typescript-image-upload", 3 | "version": "1.0.0", 4 | "description": "Software of development with TypeScript,Nodejs,MongoDB,etc", 5 | "main": "index.js", 6 | "scripts": { 7 | "dev": "concurrently \"tsc -w\" \"nodemon dist/index.js\"" 8 | }, 9 | "keywords": [], 10 | "author": "Daniel Alejo Alvarez", 11 | "license": "MIT", 12 | "devDependencies": { 13 | "@types/cors": "^2.8.6", 14 | "@types/express": "^4.17.3", 15 | "@types/fs-extra": "^8.1.0", 16 | "@types/mongoose": "^5.7.3", 17 | "@types/morgan": "^1.9.0", 18 | "@types/multer": "^1.4.2", 19 | "@types/uuid": "^7.0.0", 20 | "concurrently": "^5.1.0", 21 | "nodemon": "^2.0.2", 22 | "typescript": "^3.8.3" 23 | }, 24 | "dependencies": { 25 | "cors": "^2.8.5", 26 | "express": "^4.17.1", 27 | "fs-extra": "^8.1.0", 28 | "mongoose": "^5.9.3", 29 | "morgan": "^1.9.1", 30 | "multer": "^1.4.2", 31 | "uuid": "^7.0.2" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app.ts: -------------------------------------------------------------------------------- 1 | import express, {Application} from "express"; 2 | import morgan from "morgan"; 3 | import cors from "cors"; 4 | 5 | import path from "path"; 6 | 7 | import indexRoutes from "./routes/index"; 8 | 9 | const app: Application = express(); 10 | 11 | app.set('port', process.env.PORT || 3000); 12 | 13 | app.use(morgan('dev')); 14 | app.use(express.json()); 15 | app.use(express.urlencoded({extended: false})); 16 | app.use(cors()); 17 | 18 | 19 | app.use('/api', indexRoutes); 20 | app.use('/uploads', express.static(path.resolve('uploads'))); 21 | 22 | export default app; -------------------------------------------------------------------------------- /src/controllers/file.controllers.ts: -------------------------------------------------------------------------------- 1 | import File from '../models/File'; 2 | import {Request,Response} from "express"; 3 | 4 | import path from "path"; 5 | import fs from "fs-extra"; 6 | 7 | export const getFiles = async (req: Request,res: Response): Promise => { 8 | const files = await File.find(); 9 | return res.json(files); 10 | } 11 | 12 | export const getFileById = async (req: Request,res: Response): Promise => { 13 | const {id} = req.params; 14 | const file = await File.findById(id); 15 | return res.json(file); 16 | } 17 | 18 | export const saveFile = async (req:Request, res: Response): Promise => { 19 | 20 | console.log(req.body); 21 | 22 | console.log(req.file); 23 | 24 | const {displayName,description,status} = req.body; 25 | 26 | const newFile = new File({ 27 | displayName, 28 | description, 29 | status 30 | }); 31 | 32 | newFile.url = req.file.path; 33 | 34 | await newFile.save(); 35 | 36 | return res.json({ 37 | msg: "File saved successfully!", 38 | newFile 39 | }); 40 | } 41 | 42 | export const deleteFile = async (req: Request,res: Response): Promise => { 43 | const {id} = req.params; 44 | const file = await File.findByIdAndRemove(id); 45 | 46 | if(file) { 47 | await fs.unlink(path.resolve(file.url)); 48 | } 49 | 50 | return res.json({ 51 | msg: "File deleted successfully!", 52 | file 53 | }); 54 | } 55 | 56 | 57 | export const updateFile = async (req: Request,res: Response): Promise => { 58 | const {id} = req.params; 59 | const {displayName,description,status} = req.body; 60 | const updFile = await File.findByIdAndUpdate(id, {displayName,description,status}, {new: true}); 61 | 62 | return res.json({ 63 | msg: "File updated successfully!", 64 | updFile 65 | }); 66 | } 67 | 68 | -------------------------------------------------------------------------------- /src/database.ts: -------------------------------------------------------------------------------- 1 | import {connect} from "mongoose"; 2 | 3 | export async function Connection() { 4 | await connect("mongodb://127.0.0.1:27017/apirestfile_db", { 5 | useNewUrlParser: true, 6 | useUnifiedTopology: true, 7 | useCreateIndex: true, 8 | useFindAndModify: false 9 | }); 10 | 11 | console.log("DB connect!"); 12 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import app from "./app"; 2 | 3 | import {Connection} from "./database"; 4 | 5 | function main() { 6 | Connection(); 7 | app.listen(app.get('port'), ()=>{ 8 | console.log(`Server running in port: http://127.0.0.1:${app.get('port')}`); 9 | }); 10 | } 11 | 12 | main(); -------------------------------------------------------------------------------- /src/libs/multer.ts: -------------------------------------------------------------------------------- 1 | import multer from "multer"; 2 | import {v4 as uuid4} from "uuid"; 3 | import path from "path"; 4 | 5 | const storage = multer.diskStorage({ 6 | destination: 'uploads', 7 | filename: (req,file,cb)=>{ 8 | cb(null, uuid4() + path.extname(file.originalname)); 9 | } 10 | }); 11 | 12 | export default multer({storage}); -------------------------------------------------------------------------------- /src/models/File.ts: -------------------------------------------------------------------------------- 1 | import {Schema,model,Document} from "mongoose"; 2 | 3 | interface IFile extends Document{ 4 | displayName: string; 5 | description: string; 6 | url: string; 7 | status: boolean; 8 | } 9 | 10 | const FileSchema = new Schema({ 11 | displayName: { 12 | type: String, 13 | required: true 14 | }, 15 | description: { 16 | type: String, 17 | required: false 18 | }, 19 | url: { 20 | type: String, 21 | required: true, 22 | max: 512 23 | }, 24 | dateReg: { 25 | type: Date, 26 | default: Date.now() 27 | }, 28 | status: { 29 | type: String, 30 | default: 'ACTIVE' 31 | } 32 | }); 33 | 34 | export default model('File', FileSchema); -------------------------------------------------------------------------------- /src/routes/index.ts: -------------------------------------------------------------------------------- 1 | import {Router} from "express"; 2 | 3 | import {getFiles, getFileById, saveFile, updateFile, deleteFile} from "../controllers/file.controllers"; 4 | 5 | import upload from '../libs/multer'; 6 | 7 | const router = Router(); 8 | 9 | router.route('/files') 10 | .post(upload.single('image'), saveFile) 11 | .get(getFiles); 12 | 13 | router.route('/files/:id') 14 | .get(getFileById) 15 | .delete(deleteFile) 16 | .put(updateFile) 17 | 18 | export default router; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | // "incremental": true, /* Enable incremental compilation */ 5 | "target": "es2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 6 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 7 | // "lib": [], /* Specify library files to be included in the compilation. */ 8 | // "allowJs": true, /* Allow javascript files to be compiled. */ 9 | // "checkJs": true, /* Report errors in .js files. */ 10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 11 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 12 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 13 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 14 | // "outFile": "./", /* Concatenate and emit output to single file. */ 15 | "outDir": "./dist/", /* Redirect output structure to the directory. */ 16 | "rootDir": "./src/", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 17 | // "composite": true, /* Enable project compilation */ 18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 19 | // "removeComments": true, /* Do not emit comments to output. */ 20 | // "noEmit": true, /* Do not emit outputs. */ 21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 24 | 25 | /* Strict Type-Checking Options */ 26 | "strict": true, /* Enable all strict type-checking options. */ 27 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 28 | // "strictNullChecks": true, /* Enable strict null checks. */ 29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 34 | 35 | /* Additional Checks */ 36 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 38 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 40 | 41 | /* Module Resolution Options */ 42 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 46 | // "typeRoots": [], /* List of folders to include type definitions from. */ 47 | // "types": [], /* Type declaration files to be included in compilation. */ 48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 49 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 52 | 53 | /* Source Map Options */ 54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 58 | 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | 63 | /* Advanced Options */ 64 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /uploads/b6f9d702-ceec-4182-9b0f-54c4edc672de.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DanielArturoAlejoAlvarez/api-rest-typescript-uploads/069b6f460d33272b805aba6d63a1c3dfb22cc707/uploads/b6f9d702-ceec-4182-9b0f-54c4edc672de.png --------------------------------------------------------------------------------