Skip to content

Commit

Permalink
created the route to add foods and saving image to firebase and route…
Browse files Browse the repository at this point in the history
… to get foods added by particular seller
  • Loading branch information
SalmanAd01 committed Oct 27, 2022
1 parent 95096a6 commit 068262e
Show file tree
Hide file tree
Showing 16 changed files with 1,654 additions and 58 deletions.
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
PORT=5000
MONGO_URI=mongodb://localhost:27017/sem5backend
MONGO_URI=mongodb://localhost:27017/sem5backend
FIREBASE_PRIVATE_KEY=
JWT_SECRET=sdlhfldsfskdfjldjflsdf
JWT_EXPIRES_IN=90d
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ out
.nuxt
dist

# Upload directory
uploads/*
!uploads/.gitkeep
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
Expand Down
11 changes: 11 additions & 0 deletions config/firebase-key.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"type": "service_account",
"project_id": "sem5backend",
"private_key_id": "91b69105a4d8c0f6a8b2c28f1dc4b109703999cf",
"client_email": "firebase-adminsdk-t2nvb@sem5backend.iam.gserviceaccount.com",
"client_id": "108687460748205065951",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-t2nvb%40sem5backend.iam.gserviceaccount.com"
}
12 changes: 12 additions & 0 deletions config/firebase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var admin = require("firebase-admin");

var serviceAccount = require("./firebase-key.json");

admin.initializeApp({
credential: admin.credential.cert({...serviceAccount,private_key:process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n')}),
storageBucket: "sem5backend.appspot.com"
});

module.exports = {
storage: admin.storage()
};
43 changes: 33 additions & 10 deletions controllers/seller.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,39 @@
const Food = require('../model/food');

const {storage} = require('../config/firebase')
const log = require('../log');
const uuidv4 = require('uuid/v4');
module.exports.addFood = async (req, res) => {
try {
const food = await Food.create({...req.body, belongsTo: req.seller});
res.status(201).json({
status: 'Food added successfully',
food,
const bucket = storage.bucket();
const file = await bucket.upload(req.file.path, {
destination: uuidv4() + req.file.originalname,
metadata: {
contentType: req.file.mimetype,
metadata: {
firebaseStorageDownloadTokens: uuidv4(),
},
},
})
const url = `https://firebasestorage.googleapis.com/v0/b/${bucket.name}/o/${encodeURIComponent(file[0].name)}?alt=media&token=${file[0].metadata.metadata.firebaseStorageDownloadTokens}`;
const food = new Food({
...req.body,
image: url,
belongsTo: req.seller._id,
});
await food.save();
res.status(201).json(food);
} catch (err) {
res.status(400).json({
status: 'Food not added',
message: err.message,
});
log.error(err);
res.status(500).json({error: err.message});
}
};

module.exports.getFoods = async (req, res) => {
try {
const foods = await Food.find({belongsTo: req.seller._id});
res.status(200).json(foods);
} catch (err) {
log.error(err);
res.status(500).json({error: err.message});
}
}
};
1 change: 1 addition & 0 deletions middleware/validateSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const validateSchema = (schema) => async (req, res, next) => {
body: req.body,
params: req.params,
query: req.query,
file: req.file,
},
);
next();
Expand Down
24 changes: 14 additions & 10 deletions model/food.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const mongoose = require('mongoose');
const validator = require('validator');
const uniqueValidator = require('mongoose-unique-validator');
const log = require('../log');

const FoodSchema = new mongoose.Schema({
name: {
Expand Down Expand Up @@ -50,20 +51,23 @@ const FoodSchema = new mongoose.Schema({
}, { timestamps: true });

// check if for same seller, food name and image is unique
FoodSchema.pre('save', (next)=> {
FoodSchema.pre('save', async function (next) {
const food = this;
food.constructor.findOne({ name: food.name, image: food.image, belongsTo: food.belongsTo }, (err, foundFood) => {
if (err) {
next(err);
} else if (foundFood) {
next(new Error('Food already exists'));
} else {
next();
}
console.log("Food pre is called", food);

const res = await Food.findOne({
$and: [
{ name: food.name },
{ belongsTo: food.belongsTo },
],
});
if (res) {
log.error('Food already exists');
throw new Error('Food already exists');
}
next();
});

FoodSchema.plugin(uniqueValidator, { message: '{PATH} already exists!' });
const Food = mongoose.model('food', FoodSchema);
Food.createIndexes();
module.exports = Food;
2 changes: 1 addition & 1 deletion model/seller.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const SellerSchema = new mongoose.Schema({
trim: true,
},
}, { timestamps: true });
SellerSchema.pre('save', async (next) => {
SellerSchema.pre('save', async function (next) {
if (!this.isModified('password')) {
next();
}
Expand Down
2 changes: 1 addition & 1 deletion model/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const UserSchema = new mongoose.Schema({
}, { timestamps: true });

UserSchema.plugin(uniqueValidator, { message: '{PATH} already exists!' });
UserSchema.pre('save', async (next) => {
UserSchema.pre('save', async function (next) {
if (!this.isModified('password')) {
next();
}
Expand Down
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,26 @@
"@adminjs/mongoose": "^3.0.0",
"adminjs": "^6.1.6",
"bcrypt": "^5.0.1",
"body-parser": "^1.20.1",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dayjs": "^1.11.6",
"dotenv": "^16.0.2",
"express": "^4.18.1",
"express-formidable": "^1.2.0",
"express-session": "^1.17.3",
"firebase": "^9.12.1",
"firebase-admin": "^11.2.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.5.4",
"mongoose-unique-validator": "^3.1.0",
"multer": "^1.4.5-lts.1",
"pino": "^8.7.0",
"pino-pretty": "^9.1.1",
"swagger-jsdoc": "^6.2.5",
"swagger-ui-express": "^4.5.0",
"tslib": "^2.4.0",
"uuid": "3.4.0",
"validator": "^13.7.0",
"yup": "^0.32.11"
},
Expand Down
25 changes: 22 additions & 3 deletions routes/seller.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const auth = require('../middleware/auth');
const { checkIfUser, checkIfSeller } = require('../middleware/requiredUser');
const validateRequest = require('../middleware/validateSchema');
const { addFoodSchema } = require('../schema/food.schema');

const upload = require('../utils/multer.util');
/**
* @swagger
* /seller/api/food/add:
Expand All @@ -31,7 +31,7 @@ const { addFoodSchema } = require('../schema/food.schema');
* description: image of the food item
* required: true
* in: formData
* type: string
* type: file
* - name: category
* description: category of the food item
* required: true
Expand Down Expand Up @@ -59,6 +59,25 @@ const { addFoodSchema } = require('../schema/food.schema');
* 500:
* description: Internal Server Error
*/
router.post('/api/food/add', validateRequest(addFoodSchema),auth,checkIfSeller,sellerController.addFood);
router.post('/api/food/add', upload.single('image'), validateRequest(addFoodSchema), auth, checkIfSeller, sellerController.addFood);

/**
* @swagger
* /seller/api/food:
* get:
* description: Get all food items
* parameters:
* - name: token
* description: token of the user
* in: cookie
* type: string
* responses:
* 200:
* description: Food items fetched successfully
* 500:
* description: Internal Server Error
* 404:
* description: Food items not found
*/
router.get('/api/food', auth, checkIfSeller, sellerController.getFoods);
module.exports = router;
4 changes: 3 additions & 1 deletion schema/food.schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ const addFoodSchema = yup.object({
name: yup.string().required(),
price: yup.number().required(),
description: yup.string().required(),
image: yup.string().required(),
category: yup.mixed().oneOf(['launch', 'dinner', 'breakfast', 'snacks']).required(),
isVeg: yup.boolean().required(),
isAvailable: yup.boolean().required(),
}),
file: yup.object({
fieldname: yup.mixed().required(),
}),
});

module.exports = {
Expand Down
6 changes: 3 additions & 3 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ const { serve, setup } = require('./utils/swagger.util');
const log = require('./log');
const cookieParser = require('cookie-parser');
const app = express();

const cors = require('cors');
app.use(cors());
const PORT = process.env.PORT || 3000;

const router = AdminJSExpress.buildRouter(adminJs);
app.use(adminJs.options.rootPath, router);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use('/user', require('./routes/auth'));
app.use('/seller', require('./routes/seller'));
Expand Down
Empty file added uploads/.gitkeep
Empty file.
26 changes: 26 additions & 0 deletions utils/multer.util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const multer = require('multer');
const storage = multer.diskStorage({
destination (req, file, cb) {
cb(null, './uploads');
},
filename (req, file, cb) {
cb(null, file.originalname);
}
})
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};

const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
})
module.exports = upload;
Loading

0 comments on commit 068262e

Please sign in to comment.