#2 connect multer for file handling

parent 96aa4852
This diff is collapsed.
......@@ -11,13 +11,19 @@
"license": "ISC",
"dependencies": {
"@types/node": "^18.15.3",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^7.0.1",
"multer": "^1.4.5-lts.1",
"ts-node-dev": "^2.0.0"
},
"devDependencies": {
"@types/body-parser": "^1.19.2",
"@types/cors": "^2.8.13",
"@types/express": "^4.17.17",
"@types/mongoose": "^5.11.97"
"@types/mongoose": "^5.11.97",
"@types/multer": "^1.4.7"
}
}
\ No newline at end of file
import express, {Express, json} from 'express';
import mongoose from 'mongoose';
import 'dotenv/config';
import {artistRouter} from './routes/artist';
import cors from 'cors';
const app: Express = express();
app.use(json());
app.use(cors());
app.use('/artists', artistRouter);
app.listen(process.env.PORT, () => {
......
import express, {Request, Response} from 'express';
import {model, Schema, connect, Document, HydratedDocument} from 'mongoose';
import {model, Schema, connect, HydratedDocument} from 'mongoose';
import multer from 'multer';
import fs from 'fs';
import path from 'path';
const upload = multer({dest: 'uploads/'});
const router = express.Router();
interface IArtist {
name: string;
image?: File;
image: File;
description: string;
}
......@@ -15,7 +19,8 @@ const artistSchema = new Schema<IArtist>({
required: true,
},
image: {
type: Buffer,
data: Buffer,
contentType: String,
},
description: {
type: String,
......@@ -31,17 +36,27 @@ const run = async () => {
run().catch((err) => console.log(err));
router.get('/', (req: Request, res: Response) => {
return res.send('Hello');
router.get('/', async (req: Request, res: Response) => {
const artists = await Artist.find();
res.send(artists);
});
router.post('/', async (req: Request, res: Response) => {
router.post(
'/',
upload.single('image'),
async (req: Request, res: Response) => {
const artist: HydratedDocument<IArtist> = new Artist({
name: req.body.name,
description: req.body.description,
image: {
data: fs.readFileSync(path.join('uploads/' + req.file?.filename)),
contentType: 'image',
},
});
await artist.save();
res.send(artist);
});
res.send('Sucessfully saved');
}
);
export {router as artistRouter};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment