I'm doing:
const audioResource = finale.resource({
model: db.models.Audio,
endpoints: ['/audios', '/audios/:id']
})
audioResource.use(multer().single("file"))
audioResource.use(resources.audio)
Where resources.audio is:
module.exports = {
create: {
write: {
before: (req, res, context) => {
console.log(Object.keys(req))
console.log(req.body)
console.log("HERE I AM!")
console.log(req.file)
}
}
}
}
However, I can't access req.file. Is it possible to set up with the multer middleware?
I think the right way to use it would be
module.exports = {
create: {
write: {
before: (req, res, context) => {
upload.single('file')(req, res, () => {
console.log(Object.keys(req))
console.log(req.body)
console.log("HERE I AM!")
console.log(req.file)
}
}
}
}
}
Related
I have these 2 controllers:
story.js
const Story = require('../models/Story');
exports.getStories = (req, res, next) => {
Story.find()
.then((stories) => {
res.render('story', {title:'StoryTata', stories});
})
.catch(() => { res.send('Sorry!'); });
};
ask.js
const Ask = require('../models/Ask');
exports.getAsks = (req, res, next) => {
Ask.find()
.then((asks) => {
res.render('ask', {title:'AskTata', asks});
})
.catch(() => { res.send('Sorry!'); });
};
And both these controllers work fine with their coupled views (stories.pug and ask.pug)
I am unable figure out my next controller where both of these controllers come together to create a dashboard type view.
dashboard controller --
const Story = require('../models/Story');
const Ask = require('../models/Ask');
/**
* GET /
* Home page.
*/
exports.getHome = (req, res) => {
Story.find()
Ask.find()
.then((stories, asks) => {
res.render('home', {stories, asks});
})
.catch(() => { res.send('Sorry!'); });
};
I will requesting getHome from my home.pug file.
What should be the correct way of doing this?
Try using the async-await approach, like this:
exports.getHome = async (req, res) => {
try {
const stories = await Story.find();
const asks = await Ask.find();
res.render('home', {stories, asks});
} catch(e) {
res.send('Sorry!');
}
};
I have this code to make a get, post, put and delete request,
const express = require("express");
const TutorialModel = require("../models/tutorialModel");
const router = express.Router();
router.post("/tutorials", async (req, res) => {
try {
const tutorial = new TutorialModel(req.body);
const createTutorial = await tutorial.save();
res.status(201).send(createTutorial);
} catch (e) {
res.status(400).send(e);
}
});
router.get("/tutorials", async (req, res) => {
try {
const TutorialsData = await TutorialModel.find();
res.status(200).send(TutorialsData);
} catch (e) {
res.status(404).send(e);
}
});
router.get("/tutorials/:id", async (req, res) => {
try {
const _id = req.params.id;
const TutorialData = await TutorialModel.findById(_id);
if (!TutorialData) {
res.status(404).send();
} else {
res.send(TutorialData);
}
} catch (e) {
res.status(500).send(e);
}
});
router.get("/tutorials/:title", async (req, res) => {
try {
const _title = req.params.title;
const TutorialData = await TutorialModel.find({ title: _title });
if (!TutorialData) {
res.status(404).send();
} else {
res.send(TutorialData);
}
} catch (e) {
res.status(500).send(e);
}
});
router.put("/tutorials/:id", async (req, res) => {
try {
const _id = req.params.id;
const updateTutorial = await TutorialModel.findByIdAndUpdate(
_id,
req.body,
{ new: true }
);
res.send(updateTutorial);
} catch (e) {
res.status(400).send(e);
}
});
// Deleting student data by its Id
router.delete("/tutorials/:id", async (req, res) => {
try {
const _id = req.params.id;
const deleteTutorial = await TutorialModel.findByIdAndDelete(_id);
if (!_id) {
return res.status(400).send();
} else {
res.send(deleteTutorial);
}
} catch (e) {
res.status(500).send(e);
}
});
router.delete("/tutorials", async (req, res) => {
try {
const deleteTutorial = await TutorialModel.remove();
if (!deleteTutorial) {
return res.status(400).send();
}
else {
res.send(deleteTutorial);
}
} catch (e) {
res.status(500).send(e);
}
});
module.exports = router;
I've successfully made all request including get request with 'id' But when I try to make get request using 'title' parameter I'm getting data of get request of "/tutorials" not of "tutorials/:title". What is the issue? Can anyone tell me please?
The route GET "/tutorials/:id" will catch all your GET requests like /tutorials/something. It does not distinguish if you pass an id or a title.
:id is used to tell Express to capture the something path in the URL in req.params.id. That's all.
If you want to have another route to get tutorials by title, you should use another form. For example, GET "/tutorialsByTitle/:title".
I am working on express Api with mongoose to create get Api for my project. I was able to make one get call successfully. But I am not sure how to make api for sorting data by different fields
Model
id,
productName,
costPrice,
soldPrice
router.get("/sellProduct",
(req, res, next) => {
// condition
if(req.query.product){
Product.find({prodName:req.query.product} ).then(data => {
if (data) {
res.status(200).send(data)
}
})
}
// WHAT SHOULD BE THE SORT LOGIC TO SORT BY DIFF FIELD
else if(req.query.sortBy){
Product.find({}).sort().then(data => {
if (data) {
res.status(200).send(data)
}
})
}
else{
Product.find().then(data => {
if (data) {
res.status(200).send(data)
}
})
}
});
I am beigneer and trying my best but any help will be appreciated
You can build the parameters for .find and .sort dynamically:
router.get("/sellProduct", (req, res, next) => {
const findParams = {};
const sortParams = {
lowerCostPrice: { costPrice: 1 },
higherCostPrice: { costPrice: -1 },
lowerSoldPrice: { soldPrice: 1 },
higherSoldPrice: { soldPrice: -1 },
/* add more sort options ... */
}[req.query.sortBy];
if (req.query.product) findParams.prodName = req.query.product
/* add more search options ... */
Product.find(findParams).sort(sortParams).then(data => {
if (data) {
res.status(200).send(data);
} else {
res.status(404);
}
}).catch(err => {
console.log(err);
res.status(500);
});
});
If I understand you question correctly, you can add a switch block and depending on the passed value, sort the products:
router.get('/sellProduct', (req, res, next) => {
let result;
// ...
if (req.query.sortBy) {
switch (req.query.sortBy) {
case 'lowerCostPrice': {
result = await Product.find({}).sort({ price: 'asc' });
break;
}
case 'higherCostPrice': {
result = await Product.find({}).sort({ price: 'desc' });
break;
}
// and so on...
}
}
// ...
res.status(200).send(result);
});
I try to put router.post in a function and export it to app.js. But it didn't take effect. Here is my code.
crypto.js
function getPublicKey() {
console.log('111');
router.post('/get-public-key', (req, res) => {
fs.readFile(__dirname + '/keys/rsa-pub.pem', 'utf8', (err, data) => {
if (err) {
throw err
} else {
res.send(data)
}
})
});
}
module.exports = {
getPublicKey
}
app.js
const cryptoRouter = require('./modules/crypto/router');
cryptoRouter.getPublicKey();
It printed '111'.But I cannot POST /get-public-key.
How should I do?Thanks!
I think getPublicKey should return the public key instead
function getPublicKey() {
fs.readFile(__dirname + '/keys/rsa-pub.pem', 'utf8', (err, data) => {
if (err) {
throw err
}
return data
})
}
Then, in app.js
app.post('/get-public-key', (req, res) => {
res.send(getPublicKey)
})
Edit
If you wanna use router, you should do like this:
// ./routes/somewhere.js
const router = require('express').Router()
router.post('/something', (req, res) => {
res.send('You made it!')
})
module.exports = router
Then
// ./app.js
app.use('/somewhere', require('./routes/somewhere'))
Finally, you can make a post request to /somewhere/something.
You can pass the instance of app to your function and return the route
function getPublicKey(app) {
console.log('111');
return app.post('/get-public-key', (req, res) => {
fs.readFile(__dirname + '/keys/rsa-pub.pem', 'utf8', (err, data) => {
if (err) {
throw err
} else {
res.send(data)
}
})
})
}
module.exports = {
getPublicKey
}
Then in your app.js you could simply invoke by passing in the instance of app:
const cryptoRouter = require('./modules/crypto/router');
cryptoRouter.getPublicKey(app);
I have the following function where I am using the cryptocompare npm package:
getPrice: function(coin){
cc.price(coin, 'USD')
.then(prices => {
console.log(prices);
return prices;
}).catch(console.error)
}
// https://github.com/markusdanek/crypto-api/blob/master/server/helper/cryptocompare.js
Now I want to set up an Express server to open http://localhost:9000/current and to display the current "price".
So I have my controller which looks like this:
module.exports = {
getCurrentPrice: function(req, res, next) {
getPrice('ETH', function(price);
}
};
// https://github.com/markusdanek/crypto-api/blob/master/server/controllers/CryptoController.jshttps://github.com/markusdanek/crypto-api/blob/master/server/controllers/CryptoController.js
My route:
var controllers = require('../controllers'),
app = require('express').Router();
module.exports = function(app) {
app.get('/current', controllers.crypto.getCurrentPrice);
};
When I open now http://localhost:9000/current I only get the current price in my console, but not in my browser.
How can I also set the response to the value?
I tried this but failed:
module.exports = {
getCurrentPrice: function(req, res, next) {
getPrice('ETH', function(price){
res.status(200).json(price);
});
}
};
I guess thats the wrong way to call a callback.. do I have to modify my helper function or anything else?
My project is also on Github for further references: https://github.com/markusdanek/crypto-api
below may help you
module.exports = {
getCurrentPrice: function(req, res, next) {
cc.price('ETH', 'USD')
.then(prices => {
console.log(prices);
res.json(prices)
})
.catch(err=>{
console.error(err)
return next(err);
})
}
};