Implemented new APIs and resolved bugs in existing ones. Added functionality for song uploads and improved data retrieval in song-related endpoints. Enhanced overall API performance and ensured proper error handling.
This commit is contained in:
parent
fc5abc0432
commit
ac2ce43707
|
@ -1 +1,2 @@
|
||||||
node_modules/
|
node_modules
|
||||||
|
package-lock.json
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
const User = require('../models/user.model');
|
const {User} = require('../models/user.model');
|
||||||
const constant = require('../util/constant')
|
const constant = require('../util/constant')
|
||||||
const bcrypt = require('bcryptjs');
|
const bcrypt = require('bcryptjs');
|
||||||
const objectConverter = require('../util/objectConverter');
|
const objectConverter = require('../util/objectConverter');
|
||||||
|
@ -6,86 +6,86 @@ const objectConverter = require('../util/objectConverter');
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const createAdmin = async (req, res) => {
|
// const createAdmin = async (req, res) => {
|
||||||
|
|
||||||
try {
|
// try {
|
||||||
let user = await User.findOne({ userTypes: constant.userTypes.admin })
|
// let user = await User.findOne({ userTypes: constant.userTypes.admin })
|
||||||
|
|
||||||
if (user) {
|
// if (user) {
|
||||||
console.log('Admin Already Created', user);
|
// console.log('Admin Already Created', user);
|
||||||
|
|
||||||
return res.status(201).send({
|
// return res.status(201).send({
|
||||||
message: 'Admin already created'
|
// message: 'Admin already created'
|
||||||
});
|
// });
|
||||||
}
|
// }
|
||||||
|
|
||||||
|
|
||||||
let obj = {
|
// let obj = {
|
||||||
email: req.body.email ? req.body.email : undefined,
|
// email: req.body.email ? req.body.email : undefined,
|
||||||
password: req.body.password ? bcrypt.hashSync(req.body.password) : undefined,
|
// password: req.body.password ? bcrypt.hashSync(req.body.password) : undefined,
|
||||||
userName: 'Admin',
|
// userName: 'Admin',
|
||||||
userTypes: constant.userTypes.admin
|
// userTypes: constant.userTypes.admin
|
||||||
|
|
||||||
}
|
// }
|
||||||
if (req.file) {
|
// if (req.file) {
|
||||||
const { filename, path } = req.file;
|
// const { filename, path } = req.file;
|
||||||
obj["image"] = {
|
// obj["image"] = {
|
||||||
fileName: filename,
|
// fileName: filename,
|
||||||
fileAddress: path
|
// fileAddress: path
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
console.log(obj);
|
// console.log(obj);
|
||||||
await User.create(obj);
|
// await User.create(obj);
|
||||||
res.status(200).send({
|
// res.status(200).send({
|
||||||
errorCode: 200,
|
// errorCode: 200,
|
||||||
message: 'Admin Got Created'
|
// message: 'Admin Got Created'
|
||||||
})
|
// })
|
||||||
console.log('Admin got created');
|
// console.log('Admin got created');
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
} catch (err) {
|
// } catch (err) {
|
||||||
console.log(err);
|
// console.log(err);
|
||||||
res.status(500).send({
|
// res.status(500).send({
|
||||||
errorCode: 500,
|
// errorCode: 500,
|
||||||
message: 'Internal Error while creating Admin'
|
// message: 'Internal Error while creating Admin'
|
||||||
})
|
// })
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
const getList = async (req, res) => {
|
const getList = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const page = parseInt(req.query.page) || 1;
|
const page = parseInt(req.query.page) || 1;
|
||||||
const limit = parseInt(req.query.limit) || 10;
|
const limit = parseInt(req.query.limit) || 5;
|
||||||
const skipIndex = (page - 1) * limit;
|
const skipIndex = (page - 1) * limit;
|
||||||
const searchQuery = req.query.search || ''; // Get search query from request query parameters
|
const searchQuery = req.query.search || '';
|
||||||
|
|
||||||
let obj = {
|
let obj = {
|
||||||
userTypes: constant.userTypes.customer
|
userTypes: constant.userTypes.customer
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add search functionality
|
|
||||||
if (searchQuery) {
|
if (searchQuery) {
|
||||||
obj.$or = [
|
obj.$or = [
|
||||||
{ username: { $regex: searchQuery, $options: 'i' } }, // Case-insensitive search for username
|
{ username: { $regex: searchQuery, $options: 'i' } },
|
||||||
{ email: { $regex: searchQuery, $options: 'i' } } // Case-insensitive search for email
|
{ email: { $regex: searchQuery, $options: 'i' } }
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
const users = await User.find(obj)
|
const users = await User.find(obj)
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.skip(skipIndex);
|
.skip(skipIndex)
|
||||||
const totalCount = await User.countDocuments(obj);
|
.lean(); // Convert to plain JavaScript objects for manipulation
|
||||||
|
|
||||||
|
const totalCount = await User.countDocuments(obj); // Get total count of matching documents
|
||||||
|
|
||||||
console.log('users', users)
|
console.log('users', users)
|
||||||
return res.status(200).send({
|
return res.status(200).send({
|
||||||
status: 200,
|
status: 200,
|
||||||
message: 'Users retrieved successfully',
|
message: 'Users retrieved successfully',
|
||||||
users: users,
|
users: users,
|
||||||
|
total_users: totalCount, // Include total data count in the response
|
||||||
total_pages: Math.ceil(totalCount / limit),
|
total_pages: Math.ceil(totalCount / limit),
|
||||||
current_page: page
|
current_page: page
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
@ -98,6 +98,8 @@ const getList = async (req, res) => {
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const update = async (req, res) => {
|
const update = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const adminId = req.userId;
|
const adminId = req.userId;
|
||||||
|
@ -304,7 +306,7 @@ const changePassword = async (req, res) => {
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
createAdmin,
|
// createAdmin,
|
||||||
updateProfile,
|
updateProfile,
|
||||||
getList,
|
getList,
|
||||||
adminProfile,
|
adminProfile,
|
||||||
|
|
|
@ -3,6 +3,8 @@ const Artist = require('../models/artist.model');
|
||||||
|
|
||||||
const createArtist = async (req, res) => {
|
const createArtist = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
console.log(req,"=============================>123");
|
||||||
|
console.log(req.body,"hooooo")
|
||||||
const { ArtistName } = req.body;
|
const { ArtistName } = req.body;
|
||||||
|
|
||||||
// Check if the required fields are present in the request body
|
// Check if the required fields are present in the request body
|
||||||
|
@ -21,7 +23,6 @@ const createArtist = async (req, res) => {
|
||||||
const baseUrl = `${req.protocol}://${req.get('host')}`;
|
const baseUrl = `${req.protocol}://${req.get('host')}`;
|
||||||
const imagePath = `uploads/${req.file.filename}`;
|
const imagePath = `uploads/${req.file.filename}`;
|
||||||
const imageUrl = `${baseUrl}/${imagePath}`;
|
const imageUrl = `${baseUrl}/${imagePath}`;
|
||||||
console.log("🚀 ~ createArtist ~ imageUrl:", imageUrl);
|
|
||||||
|
|
||||||
obj["image"] = {
|
obj["image"] = {
|
||||||
fileName: req.file.filename,
|
fileName: req.file.filename,
|
||||||
|
@ -29,14 +30,13 @@ const createArtist = async (req, res) => {
|
||||||
};
|
};
|
||||||
obj["imageUrl"] = imageUrl;
|
obj["imageUrl"] = imageUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save 'obj' to the database
|
// Save 'obj' to the database
|
||||||
const newArtist = await Artist.create(obj);
|
const newArtist = await Artist.create(obj);
|
||||||
console.log("🚀 ~ createArtist ~ newArtist:", newArtist);
|
console.log("🚀 ~ createArtist ~ newArtist:", newArtist);
|
||||||
|
|
||||||
// Return a success response with the newly created Artist
|
// Return a success response with the newly created Artist
|
||||||
return res.status(201).send({
|
return res.status(200).send({
|
||||||
error_code: 201,
|
error_code: 200,
|
||||||
message: "Artist created",
|
message: "Artist created",
|
||||||
Artist: newArtist
|
Artist: newArtist
|
||||||
});
|
});
|
||||||
|
@ -188,33 +188,55 @@ const changeArtistStatus = async (req, res) => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getAllArtist = async (req, res) => {
|
const allArtist =async(req,res)=>{
|
||||||
try {
|
try {
|
||||||
// Pagination parameters
|
|
||||||
const page = parseInt(req.query.page) || 1;
|
|
||||||
const limit = parseInt(req.query.limit) || 10;
|
|
||||||
const skip = (page - 1) * limit;
|
|
||||||
|
|
||||||
// Search query
|
|
||||||
const searchQuery = req.query.search || '';
|
|
||||||
|
|
||||||
// Fetch artists with pagination and search
|
|
||||||
const artistsQuery = Artist.find();
|
|
||||||
if (searchQuery) {
|
|
||||||
artistsQuery.where('ArtistName').regex(new RegExp(searchQuery, 'i'));
|
|
||||||
}
|
|
||||||
|
|
||||||
const artists = await artistsQuery.skip(skip).limit(limit);
|
|
||||||
|
|
||||||
// Count total number of artists for pagination
|
|
||||||
const totalCount = await Artist.countDocuments(artistsQuery.getQuery());
|
|
||||||
|
|
||||||
|
const artists = await Artist.find();
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
error_code: 200,
|
error_code: 200,
|
||||||
message: 'Artists fetched successfully',
|
message: 'Artists fetched successfully',
|
||||||
|
artists
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error inside getAllArtist controller:', error);
|
||||||
|
return res.status(500).json({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Internal Server Error'
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getAllArtist = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const page = parseInt(req.query.page) || 1;
|
||||||
|
const limit = parseInt(req.query.limit) || 5;
|
||||||
|
const skip = (page - 1) * limit;
|
||||||
|
|
||||||
|
const searchQuery = req.query.search || '';
|
||||||
|
|
||||||
|
// Build the query for fetching artists with pagination and search
|
||||||
|
const artistQuery = Artist.find({
|
||||||
|
ArtistName: { $regex: searchQuery, $options: 'i' }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Execute the query with pagination
|
||||||
|
const artists = await artistQuery.skip(skip).limit(limit);
|
||||||
|
|
||||||
|
// Count total number of artists for pagination
|
||||||
|
const totalCount = await Artist.countDocuments({
|
||||||
|
ArtistName: { $regex: searchQuery, $options: 'i' }
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Artists retrieved successfully',
|
||||||
artists,
|
artists,
|
||||||
currentPage: page,
|
total_count: totalCount,
|
||||||
totalPages: Math.ceil(totalCount / limit)
|
page,
|
||||||
|
limit
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error inside getAllArtist controller:', error);
|
console.error('Error inside getAllArtist controller:', error);
|
||||||
|
@ -225,10 +247,14 @@ const getAllArtist = async (req, res) => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
createArtist,
|
createArtist,
|
||||||
updateArtist,
|
updateArtist,
|
||||||
deleteArtist,
|
deleteArtist,
|
||||||
getArtistById,
|
getArtistById,
|
||||||
changeArtistStatus, getAllArtist
|
changeArtistStatus, getAllArtist,
|
||||||
|
allArtist
|
||||||
};
|
};
|
||||||
|
|
|
@ -346,8 +346,8 @@ const getAlbums = async (req, res) => {
|
||||||
{ shortDescription: { $regex: searchQuery, $options: 'i' } }
|
{ shortDescription: { $regex: searchQuery, $options: 'i' } }
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
.populate('categoryId') // Populate categoryId field
|
.populate('categoryId')
|
||||||
.populate('subcategoryId') // Populate subcategoryId field
|
.populate('subcategoryId')
|
||||||
.skip(skip)
|
.skip(skip)
|
||||||
.limit(limit);
|
.limit(limit);
|
||||||
|
|
||||||
|
@ -386,6 +386,134 @@ const getAlbums = async (req, res) => {
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// const getAlbums = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// // Pagination parameters
|
||||||
|
// const { page = 1, limit = 10 } = req.query;
|
||||||
|
// const skip = (page - 1) * limit;
|
||||||
|
// const searchQuery = req.query.search || '';
|
||||||
|
|
||||||
|
|
||||||
|
// const matchQuery = {
|
||||||
|
// SubCategoriesName: { $regex: searchQuery, $options: 'i' },
|
||||||
|
// 'CategoriesId.deleted': { $ne: true },
|
||||||
|
// 'subcategoryId.deleted':{$ne:true},
|
||||||
|
// 'deleted': { $ne: true }
|
||||||
|
// };
|
||||||
|
|
||||||
|
// // Aggregation pipeline to exclude albums with deleted categories or subcategories
|
||||||
|
// const albums = await Album.aggregate([
|
||||||
|
// {$match:matchQuery },
|
||||||
|
// {
|
||||||
|
// $lookup: {
|
||||||
|
// from: 'categories',
|
||||||
|
// localField: 'categoryId',
|
||||||
|
// foreignField: '_id',
|
||||||
|
// as: 'category'
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// $lookup: {
|
||||||
|
// from: 'subcategories',
|
||||||
|
// localField: 'subcategoryId',
|
||||||
|
// foreignField: '_id',
|
||||||
|
// as: 'subcategory'
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// $match: {
|
||||||
|
// $and: [
|
||||||
|
// { 'category': { $not: { $elemMatch: { 'deleted': true } } } }, // Exclude albums with deleted categories
|
||||||
|
// { 'subcategory': { $not: { $elemMatch: { 'deleted': true } } } } // Exclude albums with deleted subcategories
|
||||||
|
// ]
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
// { $skip: skip },
|
||||||
|
// { $limit: limit }
|
||||||
|
// ]);
|
||||||
|
|
||||||
|
// const totalCount = await Album.countDocuments({
|
||||||
|
// $or: [
|
||||||
|
// { albumName: { $regex: searchQuery, $options: 'i' } },
|
||||||
|
// { shortDescription: { $regex: searchQuery, $options: 'i' } }
|
||||||
|
// ]
|
||||||
|
// });
|
||||||
|
|
||||||
|
// const totalPages = Math.ceil(totalCount / limit);
|
||||||
|
|
||||||
|
// return res.status(200).json({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: "Albums retrieved successfully",
|
||||||
|
// data: albums.map(album => ({
|
||||||
|
// _id: album._id,
|
||||||
|
// status: album.status,
|
||||||
|
// image: album.image,
|
||||||
|
// imageUrl: album.imageUrl,
|
||||||
|
// albumName: album.albumName,
|
||||||
|
// shortDescription: album.shortDescription,
|
||||||
|
// category: album.category[0] ? album.category[0].name : null,
|
||||||
|
// subcategory: album.subcategory[0] ? album.subcategory[0].SubCategoriesName : null
|
||||||
|
// })),
|
||||||
|
// totalPages: totalPages,
|
||||||
|
// currentPage: page
|
||||||
|
// });
|
||||||
|
// } catch (err) {
|
||||||
|
// console.log("Error inside GetAlbums Controller", err);
|
||||||
|
// return res.status(500).json({
|
||||||
|
// error_code: 500,
|
||||||
|
// message: "Internal Server Error"
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
|
const allAlbums =async(req,res)=>{
|
||||||
|
try {
|
||||||
|
|
||||||
|
const albums = await Album.find();
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Albums fetched successfully',
|
||||||
|
albums
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error inside GetAlbums Controller", err);
|
||||||
|
return res.status(500).json({
|
||||||
|
error_code: 500,
|
||||||
|
message: "Internal Server Error"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const getsubcategories = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { subcategoryId } = req.params;
|
||||||
|
|
||||||
|
|
||||||
|
const subCategories = await Album.find({ subcategoryId: subcategoryId });
|
||||||
|
if (!subCategories || subCategories.length === 0) {
|
||||||
|
return res.status(400).send({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'subCategories not found for the given subCategories ID'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Categories retrieved successfully',
|
||||||
|
subCategories: subCategories
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error inside getCategories', err);
|
||||||
|
res.status(500).send({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Internal Server Error'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -395,7 +523,9 @@ module.exports = {
|
||||||
deleteAlbum,
|
deleteAlbum,
|
||||||
changeAlbumStatus,
|
changeAlbumStatus,
|
||||||
getAlbums,
|
getAlbums,
|
||||||
deletMany
|
allAlbums,
|
||||||
|
deletMany,
|
||||||
|
getsubcategories
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,97 +1,251 @@
|
||||||
const bcrypt = require('bcryptjs');
|
const bcrypt = require('bcryptjs');
|
||||||
const User = require('../models/user.model');
|
const { User } = require('../models/user.model');
|
||||||
|
const multer = require('multer');
|
||||||
|
|
||||||
|
|
||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const authConfig = require('../configs/auth.config');
|
const authConfig = require('../configs/auth.config');
|
||||||
const constant = require('../util/constant')
|
const constant = require('../util/constant')
|
||||||
const nodemailer = require('nodemailer');
|
const nodemailer = require('nodemailer');
|
||||||
|
|
||||||
|
const sendOTPByEmail = async (email, otp) => {
|
||||||
|
try {
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
service: 'gmail', // e.g., 'Gmail'
|
||||||
|
auth: {
|
||||||
|
user: 'ay2087355@gmail.com',
|
||||||
|
pass: 'phbcdqcqdvsgdlsb'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const signUp = async(req,res) => {
|
const mailOptions = {
|
||||||
try{
|
from: 'checkdemo02@gmail.com',
|
||||||
const obj = {
|
to: email,
|
||||||
name : req.body.name,
|
subject: 'Your OTP Code',
|
||||||
password : bcrypt.hashSync(req.body.password,8),
|
text: `Your OTP code is: ${otp}`
|
||||||
email : req.body.email,
|
};
|
||||||
registerWith : constant.registerWith.Email
|
|
||||||
}
|
|
||||||
const generateOTP = () => {
|
|
||||||
return Math.floor(10000 + Math.random() * 90000);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Send the email
|
||||||
const email = req.body.email;
|
const info = await transporter.sendMail(mailOptions);
|
||||||
const otp = generateOTP();
|
console.log('OTP email sent:', info.response);
|
||||||
obj['otp'] = otp;
|
return info.response;
|
||||||
const user = await User.create(obj);
|
} catch (error) {
|
||||||
|
console.error('Error sending OTP email:', error);
|
||||||
const transporter = nodemailer.createTransport({
|
throw error;
|
||||||
service: 'Gmail', // e.g., 'Gmail'
|
|
||||||
auth: {
|
|
||||||
user: 'checkdemo02@gmail.com',
|
|
||||||
pass: 'vqdoqmekygtousli'
|
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
|
const generateOTP = () => {
|
||||||
const mailOptions = {
|
return Math.floor(10000 + Math.random() * 90000);
|
||||||
from: 'checkdemo02@gmail.com',
|
|
||||||
to: req.body.email, // The user's email
|
|
||||||
subject: 'Your OTP Code',
|
|
||||||
text: `Your OTP code is: ${otp}`
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Send the email
|
|
||||||
transporter.sendMail(mailOptions, (error, info) => {
|
|
||||||
if (error) {
|
|
||||||
console.error('Error sending OTP email:', error);
|
|
||||||
return res.status(500).send({
|
|
||||||
errorCode : 500,
|
|
||||||
message : "Mail not Send"
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
console.log('OTP email sent:', info.response);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
const token = jwt.sign({id:user._id},authConfig.secretKey,{
|
|
||||||
expiresIn : 6000000
|
|
||||||
});
|
|
||||||
|
|
||||||
|
const signUp = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { name, email, password, confirmPassword } = req.body;
|
||||||
|
|
||||||
|
if (password !== confirmPassword) {
|
||||||
|
return res.status(400).send({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'Password and confirm password do not match'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return res.status(201).send({
|
let existingUser = await User.findOne({ email: email });
|
||||||
error_code : 200,
|
|
||||||
message : 'Success',
|
if (existingUser) {
|
||||||
otp : otp,
|
if (existingUser.otpVerifly == true) {
|
||||||
accessToken : token
|
return res.status(401).send({
|
||||||
})
|
error_code: 401,
|
||||||
}catch(err){
|
message: 'Email already registered'
|
||||||
console.log(err);
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existingUser.otpVerifly == false) {
|
||||||
|
existingUser.password = bcrypt.hashSync(password, 8);
|
||||||
|
existingUser.otp = generateOTP();
|
||||||
|
|
||||||
|
// Send OTP email
|
||||||
|
await sendOTPByEmail(email, existingUser.otp);
|
||||||
|
|
||||||
|
// Save updated user
|
||||||
|
existingUser = await existingUser.save();
|
||||||
|
|
||||||
|
return res.status(200).send({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'User registered successfully. ',
|
||||||
|
email: email,
|
||||||
|
otp: existingUser.otp,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Create new user
|
||||||
|
const obj = {
|
||||||
|
name: name,
|
||||||
|
password: bcrypt.hashSync(password, 8),
|
||||||
|
email: email,
|
||||||
|
registerWith: constant.registerWith.Email,
|
||||||
|
otp: generateOTP() // Assuming generateOTP() function is defined
|
||||||
|
};
|
||||||
|
|
||||||
|
// Send OTP email
|
||||||
|
await sendOTPByEmail(email, obj.otp);
|
||||||
|
|
||||||
|
// Create new user
|
||||||
|
const user = await User.create(obj);
|
||||||
|
return res.status(200).send({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'User registered successfully. ',
|
||||||
|
email: email,
|
||||||
|
otp: obj.otp,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
res.status(500).send({
|
res.status(500).send({
|
||||||
error_code : 200,
|
error_code: 500,
|
||||||
message : 'Failed'
|
message: 'Failed'
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// const signUp = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// const obj = {
|
||||||
|
// name: req.body.name,
|
||||||
|
// password: bcrypt.hashSync(req.body.password, 8),
|
||||||
|
// email: req.body.email,
|
||||||
|
// registerWith: constant.registerWith.Email
|
||||||
|
// }
|
||||||
|
// const generateOTP = () => {
|
||||||
|
// return Math.floor(10000 + Math.random() * 90000);
|
||||||
|
// }
|
||||||
|
|
||||||
|
|
||||||
|
// const email = req.body.email;
|
||||||
|
// const otp = generateOTP();
|
||||||
|
// obj['otp'] = otp;
|
||||||
|
// const user = await User.create(obj);
|
||||||
|
|
||||||
|
// const transporter = nodemailer.createTransport({
|
||||||
|
// service: 'gmail', // e.g., 'Gmail'
|
||||||
|
// auth: {
|
||||||
|
// user: 'ay2087355@gmail.com',
|
||||||
|
// pass: 'phbcdqcqdvsgdlsb'
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
|
||||||
|
// const mailOptions = {
|
||||||
|
// from: 'checkdemo02@gmail.com',
|
||||||
|
// to: req.body.email, // The user's email
|
||||||
|
// subject: 'Your OTP Code',
|
||||||
|
// text: `Your OTP code is: ${otp}`
|
||||||
|
// };
|
||||||
|
|
||||||
|
// // Send the email
|
||||||
|
// transporter.sendMail(mailOptions, (error, info) => {
|
||||||
|
// if (error) {
|
||||||
|
// console.error('Error sending OTP email:', error);
|
||||||
|
// return res.status(500).send({
|
||||||
|
// errorCode: 500,
|
||||||
|
// message: "Mail not Send"
|
||||||
|
// })
|
||||||
|
// } else {
|
||||||
|
// console.log('OTP email sent:', info.response);
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// return res.status(201).send({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'Success',
|
||||||
|
// email: email,
|
||||||
|
// otp: otp,
|
||||||
|
// })
|
||||||
|
// } catch (err) {
|
||||||
|
// console.log(err);
|
||||||
|
// res.status(500).send({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'Failed'
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const signIn = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// console.log(req.body,"===================================>123")
|
||||||
|
// const { email, password } = req.body;
|
||||||
|
|
||||||
|
// if (!email){
|
||||||
|
// return res.status(400).json({
|
||||||
|
// error_code: 400,
|
||||||
|
// message: 'Email is required'
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// if (!password){
|
||||||
|
// return res.status(400).json({
|
||||||
|
// error_code: 400,
|
||||||
|
// message: 'Password is required'
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const user = await User.findOne({ email });
|
||||||
|
// console.log("🚀 ~ signIn ~ user:", user)
|
||||||
|
// // console.log("🚀 ~ signIn ~ user:", user)
|
||||||
|
|
||||||
|
// if (!user) {
|
||||||
|
// return res.status(404).json({
|
||||||
|
// error_code: 404,
|
||||||
|
// message: 'User not found'
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// const isPasswordValid = bcrypt.compareSync(password, user.password);
|
||||||
|
// if (!isPasswordValid) {
|
||||||
|
// return res.status(401).json({
|
||||||
|
// error_code: 401,
|
||||||
|
// message: 'Password is incorrect'
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const token = jwt.sign({ id: user._id,userTypes:user.userTypes }, authConfig.secretKey, { expiresIn: '1h' });
|
||||||
|
// console.log("🚀 ~ signIn ~ token:", token)
|
||||||
|
|
||||||
|
// return res.status(200).json({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'User logged in successfully',
|
||||||
|
// accessToken: token
|
||||||
|
// });
|
||||||
|
// } catch (err) {
|
||||||
|
// console.error('Error inside signIn:', err);
|
||||||
|
// return res.status(500).json({
|
||||||
|
// error_code: 500,
|
||||||
|
// message: 'Internal Server Error'
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
const signIn = async (req, res) => {
|
const signIn = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { email, password } = req.body;
|
const email = req.body.email;
|
||||||
|
const password = req.body.password;
|
||||||
|
|
||||||
if (!email){
|
if (!email || !password) {
|
||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
error_code: 400,
|
error_code: 400,
|
||||||
message: 'Email is required'
|
message: 'Email and password are required'
|
||||||
});
|
|
||||||
}
|
|
||||||
if (!password){
|
|
||||||
return res.status(400).json({
|
|
||||||
error_code: 400,
|
|
||||||
message: 'Password is required'
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find user by email
|
|
||||||
const user = await User.findOne({ email });
|
const user = await User.findOne({ email });
|
||||||
console.log("🚀 ~ signIn ~ user:", user)
|
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return res.status(404).json({
|
return res.status(404).json({
|
||||||
|
@ -100,18 +254,23 @@ const signIn = async (req, res) => {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if the provided password matches the user's password
|
|
||||||
const isPasswordValid = bcrypt.compareSync(password, user.password);
|
const isPasswordValid = bcrypt.compareSync(password, user.password);
|
||||||
|
|
||||||
if (!isPasswordValid) {
|
if (!isPasswordValid) {
|
||||||
return res.status(401).json({
|
return res.status(401).json({
|
||||||
error_code: 401,
|
error_code: 401,
|
||||||
message: 'Password is incorrect'
|
message: 'Password is incorrect'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if (user.otpVerifly === false) {
|
||||||
|
return res.status(401).json({
|
||||||
|
error_code: 401,
|
||||||
|
message: 'User has not been verified with OTP'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Generate JWT token
|
const token = jwt.sign({ id: user._id, userTypes: user.userTypes }, authConfig.secretKey, { expiresIn: '1h' });
|
||||||
const token = jwt.sign({ id: user._id,userTypes:user.userTypes }, authConfig.secretKey, { expiresIn: '1h' });
|
// console.log("🚀 ~ signIn ~ token:", token)
|
||||||
console.log("🚀 ~ signIn ~ token:", token)
|
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
error_code: 200,
|
error_code: 200,
|
||||||
|
@ -128,34 +287,179 @@ const signIn = async (req, res) => {
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const verifyOtp = async(req,res,next) => {
|
|
||||||
try{
|
// const verifyOtp = async(req,res,next) => {
|
||||||
const otp = req.body.otp;
|
// try{
|
||||||
const user = await User.findOne({_id:req.userId});
|
// const otp = req.body.otp;
|
||||||
console.log(user.otp,otp);
|
// const user = await User.findOne({_id:req.userId});
|
||||||
if(user.otp!=otp){
|
// // console.log(user.otp,"otp");
|
||||||
return res.status(400).send({
|
// if(user.otp!=otp){
|
||||||
error_code : 400,
|
// return res.status(400).send({
|
||||||
message : 'otp is incorrect'
|
// error_code : 400,
|
||||||
})
|
// message : 'otp is incorrect'
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
// user.otpVerifly = true;
|
||||||
|
// await user.save();
|
||||||
|
// return res.status(200).send({
|
||||||
|
// error_code : 200,
|
||||||
|
// message : 'otp Verified'
|
||||||
|
// })
|
||||||
|
|
||||||
|
|
||||||
|
// }catch(err){
|
||||||
|
// console.log('Error inside verifyOtp Controller',err);
|
||||||
|
// return res.status(500).send({
|
||||||
|
// message : 'Internal Error',
|
||||||
|
// error_code : 500,
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
const verifyOtp = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { email, otp } = req.body;
|
||||||
|
const user = await User.findOne({ email });
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return res.status(200).send({
|
|
||||||
error_code : 200,
|
|
||||||
message : 'otp Verified'
|
|
||||||
})
|
|
||||||
|
|
||||||
|
if (user.otp !== otp) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'Incorrect OTP'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
}catch(err){
|
user.otpVerifly = true;
|
||||||
console.log('Error inside verifyOtp Controller',err);
|
await user.save();
|
||||||
return res.status(500).send({
|
|
||||||
message : 'Internal Error',
|
return res.status(200).json({
|
||||||
error_code : 500,
|
error_code: 200,
|
||||||
})
|
message: 'OTP verified successfully',
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in verify OTP:', error);
|
||||||
|
return res.status(500).json({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Failed'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
const resendOTP = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { email } = req.body;
|
||||||
|
|
||||||
|
const existingUser = await User.findOne({ email: email });
|
||||||
|
|
||||||
|
if (!existingUser) {
|
||||||
|
return res.status(404).json({
|
||||||
|
error_code: 404,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// if (!existingUser.otpVerifly) {
|
||||||
|
// return res.status(400).json({
|
||||||
|
// error_code: 400,
|
||||||
|
// message: 'OTP verification is not enabled for this user'
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
|
||||||
|
const newOTP = generateOTP();
|
||||||
|
|
||||||
|
existingUser.otp = newOTP;
|
||||||
|
await existingUser.save();
|
||||||
|
|
||||||
|
await sendOTPByEmail(email, newOTP);
|
||||||
|
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'OTP resent successfully'
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error inside resendOTP:', err);
|
||||||
|
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
const forgotPassword = async (req, res) => {
|
||||||
|
try {
|
||||||
|
console.log(req.body, "sahgasdh")
|
||||||
|
const { email } = req.body;
|
||||||
|
|
||||||
|
const user = await User.findOne({ email: email });
|
||||||
|
console.log("🚀 ~ forgotPassword ~ user:", user)
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(404).json({
|
||||||
|
error_code: 404,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const otp = generateOTP();
|
||||||
|
|
||||||
|
user.otp = otp;
|
||||||
|
await user.save();
|
||||||
|
|
||||||
|
await sendOTPByEmail(email, otp);
|
||||||
|
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'OTP sent to user\'s email successfully',
|
||||||
|
otp
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error inside forgotPassword:', err);
|
||||||
|
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetPassword = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { email, newPassword, confirmPassword } = req.body;
|
||||||
|
|
||||||
|
if (newPassword !== confirmPassword) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'New password and confirm password do not match'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await User.findOne({ email: email });
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(404).json({
|
||||||
|
error_code: 404,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
user.password = bcrypt.hashSync(newPassword, 8);
|
||||||
|
await user.save();
|
||||||
|
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Password reset successfully'
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error inside resetPassword:', err);
|
||||||
|
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
signIn,
|
signIn,
|
||||||
signUp,
|
signUp,
|
||||||
verifyOtp
|
verifyOtp,
|
||||||
|
resendOTP, forgotPassword, resetPassword
|
||||||
}
|
}
|
|
@ -4,7 +4,10 @@ const Category = require('../models/categories.model');
|
||||||
|
|
||||||
const createCategories = async (req, res) => {
|
const createCategories = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
if (!req.body.categoriesName) {
|
|
||||||
|
console.log(req.body)
|
||||||
|
const name =req.body;
|
||||||
|
if (!req.body.name) {
|
||||||
return res.status(400).send({
|
return res.status(400).send({
|
||||||
error_code: 400,
|
error_code: 400,
|
||||||
message: "Category name is required"
|
message: "Category name is required"
|
||||||
|
@ -12,7 +15,7 @@ const createCategories = async (req, res) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
let obj = {
|
let obj = {
|
||||||
name: req.body.categoriesName,
|
name: req.body.name ,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (req.file) {
|
if (req.file) {
|
||||||
|
|
|
@ -1,24 +1,24 @@
|
||||||
const Language = require('../models/language.model');
|
const Language = require('../models/language.model');
|
||||||
|
|
||||||
// Function to create a new language
|
// Function to create a new language
|
||||||
const createLanguage = async function (req, res) {
|
const createLanguage = async function (req, res) {
|
||||||
try {
|
try {
|
||||||
let obj = {
|
let obj = {
|
||||||
language: req.body.language ? req.body.language : undefined
|
language: req.body.language ? req.body.language : undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!obj.language) {
|
if (!obj.language) {
|
||||||
return res.status(400).json({ error: "Language name is required" });
|
return res.status(400).json({ error_code: 400,message: "Language name is required" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call the model function to create language using obj.language
|
// Call the model function to create language using obj.language
|
||||||
const language = await Language.create({ name: obj.language });
|
const language = await Language.create({ name: obj.language });
|
||||||
|
|
||||||
// If language is created successfully, send a success response
|
// If language is created successfully, send a success response
|
||||||
res.status(201).json({ message: "Language created successfully", language });
|
res.status(200).json({ error_code: 200,message: "Language created successfully", language });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating language:', error);
|
console.error('Error creating language:', error);
|
||||||
res.status(500).json({ error: 'Failed to create language' });
|
res.status(500).json({ error_code: 500,message: 'Failed to create language' });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -30,17 +30,17 @@ const updateLanguage = async function (req, res) {
|
||||||
|
|
||||||
// Check if languageId is provided
|
// Check if languageId is provided
|
||||||
if (!languageId) {
|
if (!languageId) {
|
||||||
return res.status(400).json({ error: "Language ID is required" });
|
return res.status(400).json({ error_code: 400,error: "Language ID is required" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the language by ID and update its name
|
// Find the language by ID and update its name
|
||||||
const language = await Language.findByIdAndUpdate(languageId, { name }, { new: true });
|
const language = await Language.findByIdAndUpdate(languageId, { name }, { new: true });
|
||||||
|
|
||||||
if (!language) {
|
if (!language) {
|
||||||
return res.status(404).json({ error: "Language not found" });
|
return res.status(404).json({ error_code: 404,message: "Language not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ message: "Language updated successfully", language });
|
res.status(200).json({ error_code: 200,message: "Language updated successfully", language });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error updating language:', error);
|
console.error('Error updating language:', error);
|
||||||
res.status(500).json({ error: 'Failed to update language' });
|
res.status(500).json({ error: 'Failed to update language' });
|
||||||
|
@ -52,25 +52,25 @@ const deleteLanguage = async function (req, res) {
|
||||||
const languageId = req.params.id;
|
const languageId = req.params.id;
|
||||||
|
|
||||||
if (!languageId) {
|
if (!languageId) {
|
||||||
return res.status(400).json({ error: "Language ID is required" });
|
return res.status(400).json({ error_code: 400,message: "Language ID is required" });
|
||||||
}
|
}
|
||||||
const language = await Language.findByIdAndDelete(languageId);
|
const language = await Language.findByIdAndDelete(languageId);
|
||||||
|
|
||||||
if (!language) {
|
if (!language) {
|
||||||
return res.status(404).json({ error: "Language not found" });
|
return res.status(404).json({error_code: 404, message: "Language not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ message: "Language deleted successfully" });
|
res.json({ message: "Language deleted successfully" });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error deleting language:', error);
|
console.error('Error deleting language:', error);
|
||||||
res.status(500).json({ error: 'Failed to delete language' });
|
res.status(500).json({ error_code: 500,message: 'Failed to delete language' });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getLanguage = async function (req, res) {
|
const getLanguage = async function (req, res) {
|
||||||
try {
|
try {
|
||||||
const page = parseInt(req.query.page) || 1;
|
const page = parseInt(req.query.page) || 1;
|
||||||
const limit = parseInt(req.query.limit) || 10;
|
const limit = parseInt(req.query.limit) || 5;
|
||||||
const skip = (page - 1) * limit;
|
const skip = (page - 1) * limit;
|
||||||
|
|
||||||
const searchQuery = req.query.search || '';
|
const searchQuery = req.query.search || '';
|
||||||
|
@ -96,7 +96,7 @@ const getLanguage = async function (req, res) {
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error getting languages:', error);
|
console.error('Error getting languages:', error);
|
||||||
res.status(500).json({ error: 'Failed to get languages' });
|
res.status(500).json({ error_code: 500,message: 'Failed to get languages' });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -115,6 +115,7 @@ const changeLanguageStatus = async function (req, res) {
|
||||||
|
|
||||||
await languageData.save();
|
await languageData.save();
|
||||||
res.status(200).send({
|
res.status(200).send({
|
||||||
|
error_code: 200,
|
||||||
message: `ads status toggled successfully to ${languageData.status}`,
|
message: `ads status toggled successfully to ${languageData.status}`,
|
||||||
user: languageData
|
user: languageData
|
||||||
});
|
});
|
||||||
|
@ -127,10 +128,27 @@ const changeLanguageStatus = async function (req, res) {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//get alllanguage without pegination
|
||||||
|
|
||||||
|
const getAllLanguage = async function (req, res) {
|
||||||
|
try {
|
||||||
|
const languages = await Language.find();
|
||||||
|
res.json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Languages retrieved successfully',
|
||||||
|
languages
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting languages:', error);
|
||||||
|
res.status(500).json({ error_code: 500,message: 'Failed to get languages' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
createLanguage,
|
createLanguage,
|
||||||
updateLanguage,
|
updateLanguage,
|
||||||
deleteLanguage,
|
deleteLanguage,
|
||||||
changeLanguageStatus,
|
changeLanguageStatus,
|
||||||
getLanguage
|
getLanguage,
|
||||||
|
getAllLanguage
|
||||||
};
|
};
|
||||||
|
|
|
@ -5,20 +5,72 @@ const User = require('../models/user.model');
|
||||||
const userConst = require('../util/constant')
|
const userConst = require('../util/constant')
|
||||||
|
|
||||||
|
|
||||||
|
// const createNotification = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// const { sendTo, Type, Title, message, user } = req.body;
|
||||||
|
|
||||||
|
// // Validate sendTo value
|
||||||
|
// if (!sendTo || !['toAll', 'host', 'specific'].includes(sendTo)) {
|
||||||
|
// return res.status(400).json({ error_code: 400, message: 'Invalid sendTo value' });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// let recipients = [];
|
||||||
|
|
||||||
|
// // Determine recipients based on sendTo value
|
||||||
|
// if (sendTo === 'toAll') {
|
||||||
|
// recipients = await User.find().distinct('_id');
|
||||||
|
// } else if (sendTo === 'host') {
|
||||||
|
// const host = await User.findOne({ role: 'host' });
|
||||||
|
// if (host) recipients = [host._id];
|
||||||
|
// } else if (sendTo === 'specific') {
|
||||||
|
// recipients = await User.find({ role: 'specificRole' }).distinct('_id');
|
||||||
|
// }
|
||||||
|
// const newNotification = new Notification({
|
||||||
|
// sendTo,
|
||||||
|
// Type,
|
||||||
|
// Title,
|
||||||
|
// message,
|
||||||
|
// user,
|
||||||
|
// recipients
|
||||||
|
// });
|
||||||
|
// const savedNotification = await newNotification.save();
|
||||||
|
|
||||||
|
// return res.status(201).json({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'Notification created successfully',
|
||||||
|
// notification: savedNotification
|
||||||
|
// });
|
||||||
|
// } catch (err) {
|
||||||
|
// console.error('Error inside createNotification controller:', err);
|
||||||
|
// return res.status(500).json({
|
||||||
|
// error_code: 500,
|
||||||
|
// message: 'Internal Server Error'
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
const createNotification = async (req, res) => {
|
const createNotification = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { sendTo, Type, Title, message, user } = req.body;
|
const { sendTo, Type, Title, message, user } = req.body;
|
||||||
|
|
||||||
// Validate sendTo value
|
|
||||||
if (!sendTo || !['toAll', 'host', 'specific'].includes(sendTo)) {
|
if (!sendTo || !['toAll', 'host', 'specific'].includes(sendTo)) {
|
||||||
return res.status(400).json({ error_code: 400, message: 'Invalid sendTo value' });
|
return res.status(400).json({ error_code: 400, message: 'Invalid sendTo value' });
|
||||||
}
|
}
|
||||||
|
|
||||||
let recipients = [];
|
let recipients = [];
|
||||||
|
|
||||||
// Determine recipients based on sendTo value
|
|
||||||
if (sendTo === 'toAll') {
|
if (sendTo === 'toAll') {
|
||||||
recipients = await User.find().distinct('_id');
|
recipients = await User.find().distinct('_id');
|
||||||
|
await Promise.all(recipients.map(async (userId) => {
|
||||||
|
const newNotification = new Notification({
|
||||||
|
sendTo,
|
||||||
|
Type,
|
||||||
|
Title,
|
||||||
|
message,
|
||||||
|
user: userId,
|
||||||
|
});
|
||||||
|
console.log("🚀 ~ awaitPromise.all ~ newNotification:", newNotification)
|
||||||
|
await newNotification.save();
|
||||||
|
}));
|
||||||
} else if (sendTo === 'host') {
|
} else if (sendTo === 'host') {
|
||||||
const host = await User.findOne({ role: 'host' });
|
const host = await User.findOne({ role: 'host' });
|
||||||
if (host) recipients = [host._id];
|
if (host) recipients = [host._id];
|
||||||
|
@ -33,6 +85,7 @@ const createNotification = async (req, res) => {
|
||||||
user,
|
user,
|
||||||
recipients
|
recipients
|
||||||
});
|
});
|
||||||
|
|
||||||
const savedNotification = await newNotification.save();
|
const savedNotification = await newNotification.save();
|
||||||
|
|
||||||
return res.status(201).json({
|
return res.status(201).json({
|
||||||
|
@ -51,10 +104,11 @@ const createNotification = async (req, res) => {
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const getNotifications = async (req, res) => {
|
const getNotifications = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const page = parseInt(req.query.page) || 1;
|
const page = parseInt(req.query.page) || 1;
|
||||||
const limit = parseInt(req.query.limit) || 5;
|
const limit = parseInt(req.query.limit) || 10;
|
||||||
const skip = (page - 1) * limit;
|
const skip = (page - 1) * limit;
|
||||||
const searchQuery = req.query.search || '';
|
const searchQuery = req.query.search || '';
|
||||||
|
|
||||||
|
@ -125,6 +179,23 @@ const getNotificationId = async(req,res)=>{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//delete all notifications
|
||||||
|
const deleteAllNotifications = async (req, res) => {
|
||||||
|
try {
|
||||||
|
await Notification.deleteMany({});
|
||||||
|
res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'All notifications deleted successfully'
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error inside deleteAllNotifications controller:', err);
|
||||||
|
res.status(500).json({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Internal Server Error'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -132,7 +203,8 @@ const getNotificationId = async(req,res)=>{
|
||||||
module.exports = {
|
module.exports = {
|
||||||
createNotification,
|
createNotification,
|
||||||
getNotifications,
|
getNotifications,
|
||||||
deleteNotification,getNotificationId
|
deleteNotification,getNotificationId,
|
||||||
|
deleteAllNotifications
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,125 +1,172 @@
|
||||||
|
|
||||||
const PlayList = require('../models/playlist.model');
|
const PlayList = require('../models/playlist.model');
|
||||||
const User = require('../models/user.model');
|
const Song = require('../models/song.model');
|
||||||
|
const { User } = require('../models/user.model');
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const createPlaylist = async(req,res) => {
|
// const createPlaylist = async (req, res) => {
|
||||||
try{
|
// try {
|
||||||
console.log(req.body);
|
// console.log(req.body);
|
||||||
let obj = {
|
// let obj = {
|
||||||
name : req.body.name ? req.body.name : undefined ,
|
// name: req.body.name ? req.body.name : undefined,
|
||||||
songs : req.body.songs ? req.body.songs : undefined,
|
// songs: req.body.songs ? req.body.songs : undefined,
|
||||||
userId : req.userId
|
// userId: req.userId
|
||||||
|
// }
|
||||||
|
// const created_playlist = await PlayList.create(obj);
|
||||||
|
// const user = await User.findById(req.userId);
|
||||||
|
// await user.playlist.push(created_playlist._id);
|
||||||
|
// await user.save();
|
||||||
|
// return res.status(201).send({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'Playlist got created'
|
||||||
|
// })
|
||||||
|
|
||||||
|
// } catch (err) {
|
||||||
|
// console.log('Error inside createPlaylist ', err);
|
||||||
|
// return res.status(500).send({
|
||||||
|
// error_code: 500,
|
||||||
|
// message: 'Internal Server Error'
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
const createPlaylist = async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Check if songs are provided in the request body
|
||||||
|
if (!req.body.songs) {
|
||||||
|
return res.status(400).send({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'Songs must be provided'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Convert a single song ID to an array
|
||||||
|
const songIds = Array.isArray(req.body.songs) ? req.body.songs : [req.body.songs];
|
||||||
|
|
||||||
|
// Check if all songs exist
|
||||||
|
const songs = await Song.find({ _id: { $in: songIds } });
|
||||||
|
if (songs.length !== songIds.length) {
|
||||||
|
return res.status(400).send({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'One or more songs do not exist'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let obj = {
|
||||||
|
name: req.body.name ? req.body.name : undefined,
|
||||||
|
songs: songIds,
|
||||||
|
userId: req.userId
|
||||||
|
};
|
||||||
|
|
||||||
const created_playlist = await PlayList.create(obj);
|
const created_playlist = await PlayList.create(obj);
|
||||||
const user = await User.findById(req.userId);
|
const user = await User.findById(req.userId);
|
||||||
await user.playlist.push(created_playlist._id);
|
await user.playlist.push(created_playlist._id);
|
||||||
await user.save();
|
await user.save();
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message : 'Playlist got created'
|
message: 'Playlist created successfully'
|
||||||
})
|
});
|
||||||
|
|
||||||
}catch(err)
|
} catch (err) {
|
||||||
{
|
console.log('Error inside createPlaylist ', err);
|
||||||
console.log('Error inside createPlaylist ',err);
|
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message : 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
const addSong = async(req,res) => {
|
|
||||||
try{
|
|
||||||
|
const addSong = async (req, res) => {
|
||||||
|
try {
|
||||||
const playlist = await PlayList.findById(req.params.id);
|
const playlist = await PlayList.findById(req.params.id);
|
||||||
|
|
||||||
const obj = {
|
const obj = {
|
||||||
name : req.body.name ? req.body.name : undefined,
|
name: req.body.name ? req.body.name : undefined,
|
||||||
}
|
}
|
||||||
|
|
||||||
playlist.songs.push(req.body.song);
|
playlist.songs.push(req.body.song);
|
||||||
await playlist.save();
|
await playlist.save();
|
||||||
await playlist.updateOne(obj);
|
await playlist.updateOne(obj);
|
||||||
await playlist.save();
|
await playlist.save();
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message : 'Songs added to playlist'
|
message: 'Songs added to playlist'
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}catch(err){
|
|
||||||
console.log('Error inside update playlist',err);
|
|
||||||
|
} catch (err) {
|
||||||
|
console.log('Error inside update playlist', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message : 'Internal server Error'
|
message: 'Internal server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const removeSong = async(req,res) => {
|
const removeSong = async (req, res) => {
|
||||||
try{
|
try {
|
||||||
let playlist = await PlayList.findById(req.params.id);
|
let playlist = await PlayList.findById(req.params.id);
|
||||||
console.log(playlist);
|
console.log(playlist);
|
||||||
for(let i=0; playlist.songs.length;i++){
|
for (let i = 0; playlist.songs.length; i++) {
|
||||||
if(playlist.songs[i]==req.body.song)
|
if (playlist.songs[i] == req.body.song) {
|
||||||
{
|
playlist.songs.splice(i, 1);
|
||||||
playlist.songs.splice(i,1);
|
|
||||||
await playlist.save();
|
await playlist.save();
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message : 'Song got removed from playlist'
|
message: 'Song got removed from playlist'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}catch(err){
|
} catch (err) {
|
||||||
console.log('Error inside removeSong Controller',err);
|
console.log('Error inside removeSong Controller', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message : 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const getPlaylist = async(req,res) => {
|
const getPlaylist = async (req, res) => {
|
||||||
try{
|
try {
|
||||||
let obj = {};
|
let obj = {};
|
||||||
if(req.params.id){
|
if (req.params.id) {
|
||||||
obj['_id'] = req.params.id
|
obj['_id'] = req.params.id
|
||||||
}
|
}
|
||||||
const playlist = await PlayList.find(obj);
|
const playlist = await PlayList.find(obj);
|
||||||
|
|
||||||
return res.status(200).send(playlist);
|
return res.status(200).send(playlist);
|
||||||
|
|
||||||
}catch(err){
|
} catch (err) {
|
||||||
console.log('Error inside getPlaylist Controller',err);
|
console.log('Error inside getPlaylist Controller', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message : 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const deletePlaylist = async(req,res) => {
|
const deletePlaylist = async (req, res) => {
|
||||||
try{
|
try {
|
||||||
let id = req.params.id;
|
let id = req.params.id;
|
||||||
await PlayList.deleteOne({_id:id});
|
await PlayList.deleteOne({ _id: id });
|
||||||
const user = await User.findById(req.userId);
|
const user = await User.findById(req.userId);
|
||||||
for(let i=0;i<user.playlist.length;i++){
|
for (let i = 0; i < user.playlist.length; i++) {
|
||||||
console.log(user.playlist[i] == req.params.id);
|
console.log(user.playlist[i] == req.params.id);
|
||||||
if(user.playlist[i] == req.params.id) user.playlist.splice(i,1);
|
if (user.playlist[i] == req.params.id) user.playlist.splice(i, 1);
|
||||||
}
|
}
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
message : 'Playlist got deleted'
|
message: 'Playlist got deleted'
|
||||||
})
|
})
|
||||||
|
|
||||||
}catch(err){
|
} catch (err) {
|
||||||
console.log('Error inside deletePlaylist Controller',err);
|
console.log('Error inside deletePlaylist Controller', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
message : 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,80 +3,293 @@ const Song = require('../models/song.model');
|
||||||
const Category = require('../models/categories.model');
|
const Category = require('../models/categories.model');
|
||||||
const Subcategory = require('../models/subcategories.model');
|
const Subcategory = require('../models/subcategories.model');
|
||||||
const Album = require('../models/album.model');
|
const Album = require('../models/album.model');
|
||||||
const Artist =require('../models/artist.model')
|
const Artist = require('../models/artist.model')
|
||||||
const Language = require('../models/language.model')
|
const Language = require('../models/language.model')
|
||||||
|
|
||||||
|
|
||||||
|
// const createSong = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// const {
|
||||||
|
// categoryId,
|
||||||
|
// subcategoryId,
|
||||||
|
// albumId,
|
||||||
|
// artistId,
|
||||||
|
// title,
|
||||||
|
// musicLink,
|
||||||
|
// trackerID,
|
||||||
|
// lyrics,
|
||||||
|
// languageId
|
||||||
|
// } = req.body;
|
||||||
|
|
||||||
|
// const { coverArtImage, musicFile } = req.files;
|
||||||
|
// const [category, subcategory, album, artist, language] = await Promise.all([
|
||||||
|
// Category.findById(categoryId),
|
||||||
|
// Subcategory.findById(subcategoryId),
|
||||||
|
// Album.findById(albumId),
|
||||||
|
// Artist.findById(artistId),
|
||||||
|
// Language.findById(languageId)
|
||||||
|
// ]);
|
||||||
|
|
||||||
|
// if (!category || !subcategory || !album || !artist || !language) {
|
||||||
|
// const missingEntities = [];
|
||||||
|
// if (!category) missingEntities.push('Category');
|
||||||
|
// if (!subcategory) missingEntities.push('Subcategory');
|
||||||
|
// if (!album) missingEntities.push('Album');
|
||||||
|
// if (!artist) missingEntities.push('Artist');
|
||||||
|
// if (!language) missingEntities.push('Language');
|
||||||
|
// const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
|
||||||
|
// return res.status(404).json({ error_code: 404, message: errorMessage });
|
||||||
|
// }
|
||||||
|
// const coverArtImagePath = coverArtImage[0].path;
|
||||||
|
// const musicFilePath = musicFile[0].path;
|
||||||
|
|
||||||
|
// const baseUrl = `${req.protocol}://${req.get('host')}`;
|
||||||
|
// const coverArtImageUrl = `${baseUrl}/${coverArtImagePath}`;
|
||||||
|
// const newSong = await Song.create({
|
||||||
|
// categoryId,
|
||||||
|
// subcategoryId,
|
||||||
|
// albumId,
|
||||||
|
// artistId,
|
||||||
|
// title,
|
||||||
|
// musicLink,
|
||||||
|
// trackerID,
|
||||||
|
// lyrics,
|
||||||
|
// languageId,
|
||||||
|
// coverArtImage: {
|
||||||
|
// filename: coverArtImage[0].filename,
|
||||||
|
// fileAddress: coverArtImagePath,
|
||||||
|
// imageUrl: coverArtImageUrl
|
||||||
|
// },
|
||||||
|
// musicFile: {
|
||||||
|
// filename: musicFile[0].filename,
|
||||||
|
// fileAddress: musicFilePath
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
// return res.status(201).json({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'Song created successfully',
|
||||||
|
// song: newSong
|
||||||
|
// });
|
||||||
|
// } catch (err) {
|
||||||
|
// console.error('Error inside createSong:', err);
|
||||||
|
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
|
// const createSong = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// const {
|
||||||
|
// categoryId,
|
||||||
|
// subcategoryId,
|
||||||
|
// albumId,
|
||||||
|
// artistId,
|
||||||
|
// title,
|
||||||
|
// languageId,
|
||||||
|
// type,
|
||||||
|
// musicLink,
|
||||||
|
// trackerID,
|
||||||
|
// lyrics
|
||||||
|
// } = req.body;
|
||||||
|
|
||||||
|
// if (!type || !['1', '2'].includes(type)) {
|
||||||
|
// return res.status(400).json({ error_code: 400, message: 'Invalid or missing type parameter' });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// let musicFilePath;
|
||||||
|
// let musicFileUrl; // Define a variable to store the URL of the music file
|
||||||
|
|
||||||
|
// if (type === '1') {
|
||||||
|
// if (!musicLink || !trackerID) {
|
||||||
|
// return res.status(400).json({ error_code: 400, message: 'Music link and tracker ID are required for type 1' });
|
||||||
|
// }
|
||||||
|
// } else if (type === '2') {
|
||||||
|
// if (!req.files || !req.files.musicFile) {
|
||||||
|
// return res.status(400).json({ error_code: 400, message: 'Music file is required' });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if (!Array.isArray(req.files.musicFile) || req.files.musicFile.length === 0) {
|
||||||
|
// return res.status(400).json({ error_code: 400, message: 'Invalid music file provided' });
|
||||||
|
// }
|
||||||
|
// musicFilePath = req.files.musicFile[0].path;
|
||||||
|
// musicFileUrl = `${req.protocol}://${req.get('host')}/${musicFilePath}`; // Construct the URL of the music file
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const { coverArtImage } = req.files;
|
||||||
|
|
||||||
|
// const coverArtImagePath = coverArtImage[0].path;
|
||||||
|
// const coverArtImageUrl = `${req.protocol}://${req.get('host')}/${coverArtImagePath}`;
|
||||||
|
|
||||||
|
// const [category, subcategory, album, artist, language] = await Promise.all([
|
||||||
|
// Category.findById(categoryId),
|
||||||
|
// Subcategory.findById(subcategoryId),
|
||||||
|
// Album.findById(albumId),
|
||||||
|
// Artist.findById(artistId),
|
||||||
|
// Language.findById(languageId)
|
||||||
|
// ]);
|
||||||
|
|
||||||
|
// if (![category, subcategory, album, artist, language].every(entity => entity)) {
|
||||||
|
// const missingEntities = ['Category', 'Subcategory', 'Album', 'Artist', 'Language']
|
||||||
|
// .filter((entity, index) => ![category, subcategory, album, artist, language][index]);
|
||||||
|
// const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
|
||||||
|
// return res.status(404).json({ error_code: 404, message: errorMessage });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// let newSong;
|
||||||
|
|
||||||
|
// if (type === '1') {
|
||||||
|
// newSong = await Song.create({
|
||||||
|
// categoryId,
|
||||||
|
// subcategoryId,
|
||||||
|
// albumId,
|
||||||
|
// artistId,
|
||||||
|
// title,
|
||||||
|
// languageId,
|
||||||
|
// musicLink,
|
||||||
|
// trackerID,
|
||||||
|
// coverArtImage: {
|
||||||
|
// filename: coverArtImage[0].filename,
|
||||||
|
// fileAddress: coverArtImagePath,
|
||||||
|
// imageUrl: coverArtImageUrl
|
||||||
|
// },
|
||||||
|
// });
|
||||||
|
// } else if (type === '2') {
|
||||||
|
// newSong = await Song.create({
|
||||||
|
// categoryId,
|
||||||
|
// subcategoryId,
|
||||||
|
// albumId,
|
||||||
|
// artistId,
|
||||||
|
// title,
|
||||||
|
// languageId,
|
||||||
|
// lyrics,
|
||||||
|
// coverArtImage: {
|
||||||
|
// filename: coverArtImage[0].filename,
|
||||||
|
// fileAddress: coverArtImagePath,
|
||||||
|
// imageUrl: coverArtImageUrl
|
||||||
|
// },
|
||||||
|
// musicFile: {
|
||||||
|
// filename: req.files.musicFile[0].filename,
|
||||||
|
// fileAddress: musicFilePath,
|
||||||
|
// url: musicFileUrl // Include the URL of the music file in the database
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// return res.status(201).json({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'Song created successfully',
|
||||||
|
// song: newSong
|
||||||
|
// });
|
||||||
|
// } catch (err) {
|
||||||
|
// console.error('Error inside createSong:', err);
|
||||||
|
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
const createSong = async (req, res) => {
|
const createSong = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
console.log(req.body,"ehjyqgfe")
|
||||||
const {
|
const {
|
||||||
categoryId,
|
categoryId,
|
||||||
subcategoryId,
|
subcategoryId,
|
||||||
albumId,
|
albumId,
|
||||||
artistId,
|
artistId,
|
||||||
title,
|
title,
|
||||||
|
languageId,
|
||||||
|
type,
|
||||||
musicLink,
|
musicLink,
|
||||||
trackerID,
|
trackerID,
|
||||||
lyrics,
|
lyrics
|
||||||
languageId
|
|
||||||
} = req.body;
|
} = req.body;
|
||||||
|
|
||||||
const { coverArtImage, musicFile } = req.files;
|
if (!type || !['1', '2'].includes(type)) {
|
||||||
|
return res.status(400).json({ error_code: 400, message: 'Invalid or missing type parameter' });
|
||||||
|
}
|
||||||
|
|
||||||
// Check if both cover art image and music file are provided
|
let musicFilePath;
|
||||||
|
let musicFileUrl;
|
||||||
|
|
||||||
// Find all related documents in parallel
|
if (type === '1') {
|
||||||
const [category, subcategory, album, artist, language] = await Promise.all([
|
if (!musicLink || !trackerID) {
|
||||||
|
return res.status(400).json({ error_code: 400, message: 'Music link and tracker ID are required for type 1' });
|
||||||
|
}
|
||||||
|
} else if (type === '2') {
|
||||||
|
if (!req.files || !req.files.musicFile) {
|
||||||
|
return res.status(400).json({ error_code: 400, message: 'Music file is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(req.files.musicFile) || req.files.musicFile.length === 0) {
|
||||||
|
return res.status(400).json({ error_code: 400, message: 'Invalid music file provided' });
|
||||||
|
}
|
||||||
|
musicFilePath = req.files.musicFile[0].path;
|
||||||
|
musicFileUrl = `${req.protocol}://${req.get('host')}/${musicFilePath}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("🚀 ~ createSong ~ musicFilePath:", musicFilePath)
|
||||||
|
const { coverArtImage } = req.files;
|
||||||
|
|
||||||
|
const coverArtImagePath = coverArtImage[0].path;
|
||||||
|
const coverArtImageUrl = `${req.protocol}://${req.get('host')}/${coverArtImagePath}`;
|
||||||
|
|
||||||
|
const [category, subcategory, album, language] = await Promise.all([
|
||||||
Category.findById(categoryId),
|
Category.findById(categoryId),
|
||||||
Subcategory.findById(subcategoryId),
|
Subcategory.findById(subcategoryId),
|
||||||
Album.findById(albumId),
|
Album.findById(albumId),
|
||||||
Artist.findById(artistId),
|
|
||||||
Language.findById(languageId)
|
Language.findById(languageId)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Check if all related documents exist
|
if (![category, subcategory, album, language].every(entity => entity)) {
|
||||||
if (!category || !subcategory || !album || !artist || !language) {
|
const missingEntities = ['Category', 'Subcategory', 'Album', 'Language']
|
||||||
const missingEntities = [];
|
.filter((entity, index) => ![category, subcategory, album, language][index]);
|
||||||
if (!category) missingEntities.push('Category');
|
|
||||||
if (!subcategory) missingEntities.push('Subcategory');
|
|
||||||
if (!album) missingEntities.push('Album');
|
|
||||||
if (!artist) missingEntities.push('Artist');
|
|
||||||
if (!language) missingEntities.push('Language');
|
|
||||||
const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
|
const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
|
||||||
return res.status(404).json({ error_code: 404, message: errorMessage });
|
return res.status(402 ).json({ error_code: 402, message: errorMessage });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract file paths
|
const artistIdsArray = artistId.split(',').map(id => id.trim());
|
||||||
const coverArtImagePath = coverArtImage[0].path;
|
console.log("🚀 ~ createSong ~ artistIdsArray:", artistIdsArray)
|
||||||
const musicFilePath = musicFile[0].path;
|
|
||||||
|
|
||||||
// Construct the image URL for cover art
|
let newSong;
|
||||||
const baseUrl = `${req.protocol}://${req.get('host')}`;
|
|
||||||
const coverArtImageUrl = `${baseUrl}/${coverArtImagePath}`;
|
|
||||||
|
|
||||||
// Create the new song
|
if (type === '1') {
|
||||||
const newSong = await Song.create({
|
newSong = await Song.create({
|
||||||
categoryId,
|
categoryId,
|
||||||
subcategoryId,
|
subcategoryId,
|
||||||
albumId,
|
albumId,
|
||||||
artistId,
|
artistId: artistIdsArray,
|
||||||
title,
|
title,
|
||||||
musicLink,
|
languageId,
|
||||||
trackerID,
|
musicLink,
|
||||||
lyrics,
|
trackerID,
|
||||||
languageId,
|
coverArtImage: {
|
||||||
coverArtImage: {
|
filename: coverArtImage[0].filename,
|
||||||
filename: coverArtImage[0].filename,
|
fileAddress: coverArtImagePath,
|
||||||
fileAddress: coverArtImagePath,
|
imageUrl: coverArtImageUrl
|
||||||
imageUrl: coverArtImageUrl // Add imageUrl to coverArtImage object
|
},
|
||||||
},
|
});
|
||||||
musicFile: {
|
} else if (type === '2') {
|
||||||
filename: musicFile[0].filename,
|
newSong = await Song.create({
|
||||||
fileAddress: musicFilePath
|
categoryId,
|
||||||
}
|
subcategoryId,
|
||||||
});
|
albumId,
|
||||||
|
artistId: artistIdsArray,
|
||||||
|
title,
|
||||||
|
languageId,
|
||||||
|
lyrics,
|
||||||
|
coverArtImage: {
|
||||||
|
filename: coverArtImage[0].filename,
|
||||||
|
fileAddress: coverArtImagePath,
|
||||||
|
imageUrl: coverArtImageUrl
|
||||||
|
},
|
||||||
|
musicFile: {
|
||||||
|
filename: req.files.musicFile[0].filename,
|
||||||
|
fileAddress: musicFilePath,
|
||||||
|
url: musicFileUrl // Include the URL of the music file in the database
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log("🚀 ~ createSong ~ newSong:", newSong)
|
||||||
|
|
||||||
// Return success response with the new song
|
|
||||||
return res.status(201).json({
|
return res.status(200).json({
|
||||||
error_code: 200,
|
error_code: 200,
|
||||||
message: 'Song created successfully',
|
message: 'Song created successfully',
|
||||||
song: newSong
|
song: newSong
|
||||||
|
@ -85,18 +298,113 @@ const createSong = async (req, res) => {
|
||||||
console.error('Error inside createSong:', err);
|
console.error('Error inside createSong:', err);
|
||||||
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// const updateSong = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// const { id } = req.params;
|
||||||
|
// const updatedSong = await Song.findByIdAndUpdate(id, req.body, { new: true });
|
||||||
|
// if (!updatedSong) {
|
||||||
|
// return res.status(404).json({ error_code: 404, message: 'Song not found' });
|
||||||
|
// }
|
||||||
|
// return res.status(200).json({ error_code: 200, message: 'Song updated successfully', song: updatedSong });
|
||||||
|
// } catch (err) {
|
||||||
|
// console.error('Error inside updateSong:', err);
|
||||||
|
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
const updateSong = async (req, res) => {
|
const updateSong = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id } = req.params; // Extract the song ID from the request parameters
|
console.log(req.params,"dshgudgf")
|
||||||
const updatedSong = await Song.findByIdAndUpdate(id, req.body, { new: true }); // Find song by ID and update with the request body data
|
const {_id} = req.params;
|
||||||
|
// console.log("🚀 ~ updateSong ~ songId:", songId)
|
||||||
|
const song = await Song.findById(_id);
|
||||||
|
console.log("🚀 ~ updateSong ~ song:", song)
|
||||||
|
|
||||||
|
if (!song) {
|
||||||
|
return res.status(404).json({ error_code: 404, message: 'Song not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
categoryId,
|
||||||
|
subcategoryId,
|
||||||
|
albumId,
|
||||||
|
artistId,
|
||||||
|
title,
|
||||||
|
languageId,
|
||||||
|
type,
|
||||||
|
musicLink,
|
||||||
|
trackerID,
|
||||||
|
lyrics
|
||||||
|
} = req.body;
|
||||||
|
|
||||||
|
const updates = {};
|
||||||
|
|
||||||
|
// Input validation
|
||||||
|
if (categoryId) updates.categoryId = categoryId;
|
||||||
|
if (subcategoryId) updates.subcategoryId = subcategoryId;
|
||||||
|
if (albumId) updates.albumId = albumId;
|
||||||
|
if (artistId) {
|
||||||
|
updates.artistId = artistId.split(',').map(id => id.trim());
|
||||||
|
}
|
||||||
|
if (title) updates.title = title;
|
||||||
|
if (languageId) updates.languageId = languageId;
|
||||||
|
if (type) {
|
||||||
|
if (!['1', '2'].includes(type)) {
|
||||||
|
return res.status(400).json({ error_code: 400, message: 'Invalid type parameter' });
|
||||||
|
}
|
||||||
|
updates.type = type;
|
||||||
|
if (type === '1') {
|
||||||
|
if (!musicLink || !trackerID) {
|
||||||
|
return res.status(400).json({ error_code: 400, message: 'Music link and tracker ID are required for type 1' });
|
||||||
|
}
|
||||||
|
updates.musicLink = musicLink;
|
||||||
|
updates.trackerID = trackerID;
|
||||||
|
} else if (type === '2') {
|
||||||
|
// if (!req.files || !req.files.musicFile) {
|
||||||
|
// return res.status(400).json({ error_code: 400, message: 'Music file is required' });
|
||||||
|
// }
|
||||||
|
if (req.files && req.files.musicFile) {
|
||||||
|
const musicFilePath = req.files.musicFile[0].path;
|
||||||
|
const musicFileUrl = `${req.protocol}://${req.get('host')}/uploads/${musicFilePath}`;
|
||||||
|
updates.musicFile = {
|
||||||
|
filename: req.files.musicFile[0].filename,
|
||||||
|
fileAddress: musicFilePath,
|
||||||
|
url: musicFileUrl
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (lyrics !== undefined) updates.lyrics = lyrics;
|
||||||
|
|
||||||
|
// Update cover art image if provided
|
||||||
|
if (req.files && req.files.coverArtImage) {
|
||||||
|
const coverArtImage = req.files.coverArtImage[0];
|
||||||
|
const coverArtImagePath = coverArtImage.path;
|
||||||
|
const coverArtImageUrl = `${req.protocol}://${req.get('host')}/uploads/${coverArtImagePath}`;
|
||||||
|
updates.coverArtImage = {
|
||||||
|
filename: coverArtImage.filename,
|
||||||
|
fileAddress: coverArtImagePath,
|
||||||
|
imageUrl: coverArtImageUrl
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perform the update and return the updated song
|
||||||
|
const updatedSong = await Song.findByIdAndUpdate(_id, updates, { new: true });
|
||||||
|
|
||||||
if (!updatedSong) {
|
if (!updatedSong) {
|
||||||
return res.status(404).json({ error_code: 404, message: 'Song not found' });
|
return res.status(404).json({ error_code: 404, message: 'Song not found' });
|
||||||
}
|
}
|
||||||
return res.status(200).json({ error_code: 200, message: 'Song updated successfully', song: updatedSong });
|
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Song updated successfully',
|
||||||
|
song: updatedSong
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error inside updateSong:', err);
|
console.error('Error inside updateSong:', err);
|
||||||
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
||||||
|
@ -104,9 +412,11 @@ const updateSong = async (req, res) => {
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const deleteSong = async (req, res) => {
|
const deleteSong = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const deletedSong = await Song.findByIdAndDelete(id);
|
const deletedSong = await Song.findByIdAndDelete(id);
|
||||||
if (!deletedSong) {
|
if (!deletedSong) {
|
||||||
return res.status(404).json({ error_code: 404, message: 'Song not found' });
|
return res.status(404).json({ error_code: 404, message: 'Song not found' });
|
||||||
|
@ -117,19 +427,81 @@ const deleteSong = async (req, res) => {
|
||||||
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// const getSong = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// const { id } = req.params;
|
||||||
|
// const song = await Song.findById(id)
|
||||||
|
// .populate('languageId', 'name')
|
||||||
|
// .populate('artistId', 'ArtistName')
|
||||||
|
// .select('title musicLink trackerID lyrics coverArtImage');
|
||||||
|
|
||||||
|
// if (!song) {
|
||||||
|
// return res.status(404).json({ error_code: 404, message: 'Song not found' });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const { languageId, artistId, musicLink, trackerID, lyrics } = song;
|
||||||
|
// const languageName = languageId ? languageId.name : null;
|
||||||
|
|
||||||
|
// const artistName = artistId ? artistId.ArtistName : null;
|
||||||
|
// const imageUrl = song.coverArtImage ? song.coverArtImage.imageUrl : null;
|
||||||
|
|
||||||
|
// const songData = {
|
||||||
|
// languageName: languageName,
|
||||||
|
// artistName: artistName,
|
||||||
|
// musicLink: musicLink || null,
|
||||||
|
// trackerID: trackerID || null,
|
||||||
|
// lyrics: lyrics || null,
|
||||||
|
// imageUrl: imageUrl
|
||||||
|
// };
|
||||||
|
|
||||||
|
// return res.status(200).json({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'Song retrieved successfully',
|
||||||
|
// song: songData
|
||||||
|
// });
|
||||||
|
// } catch (err) {
|
||||||
|
// console.error('Error inside getSong:', err);
|
||||||
|
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
const getSong = async (req, res) => {
|
const getSong = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const song = await Song.findById(id)
|
const song = await Song.findById(id)
|
||||||
.populate('languageId', 'name')
|
.populate('languageId', 'name')
|
||||||
.populate('artistId', 'ArtistName')
|
.populate('artistId', 'ArtistName')
|
||||||
.select('title musicLink trackerID lyrics coverArtImage');
|
.select('title musicLink trackerID lyrics coverArtImage musicFile');
|
||||||
|
|
||||||
if (!song) {
|
if (!song) {
|
||||||
return res.status(404).json({ error_code: 404, message: 'Song not found' });
|
return res.status(404).json({ error_code: 404, message: 'Song not found' });
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.status(200).json({ error_code: 200, message: 'Song retrieved successfully', song });
|
const { languageId, artistId, musicLink, trackerID, lyrics, coverArtImage, musicFile } = song;
|
||||||
|
const languageName = languageId ? languageId.name : 'Language not available';
|
||||||
|
const artistNames = artistId.map(artist => artist.ArtistName);
|
||||||
|
const imageUrl = coverArtImage ? coverArtImage.imageUrl : 'Image not available';
|
||||||
|
const url = musicFile ? musicFile.url : 'Music file not available';
|
||||||
|
|
||||||
|
const songData = {
|
||||||
|
languageName: languageName,
|
||||||
|
artistNames: artistNames,
|
||||||
|
musicLink: musicLink || 'Music link not available',
|
||||||
|
trackerID: trackerID || 'Tracker ID not available',
|
||||||
|
lyrics: lyrics || 'Lyrics not available',
|
||||||
|
imageUrl: imageUrl,
|
||||||
|
url: url
|
||||||
|
};
|
||||||
|
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Song retrieved successfully',
|
||||||
|
song: songData
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error inside getSong:', err);
|
console.error('Error inside getSong:', err);
|
||||||
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
||||||
|
@ -138,6 +510,8 @@ const getSong = async (req, res) => {
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const changeSongStatus = async (req, res) => {
|
const changeSongStatus = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
|
@ -166,47 +540,82 @@ const changeSongStatus = async (req, res) => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const getAllSongs = async (req, res) => {
|
const getAllSongs = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { title, artist, category } = req.query;
|
const { title, artist, category, page, limit } = req.query;
|
||||||
let query = {};
|
|
||||||
|
|
||||||
// Build query object based on search fields
|
// Build match stage for filtering based on search fields
|
||||||
const searchFields = ['title', 'artist', 'category'];
|
const matchStage = {};
|
||||||
searchFields.forEach(field => {
|
['title', 'artist', 'category'].forEach(field => {
|
||||||
if (req.query[field]) {
|
if (req.query[field]) {
|
||||||
query[field] = { $regex: req.query[field], $options: 'i' };
|
matchStage[field] = { $regex: req.query[field], $options: 'i' };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Pagination parameters
|
const pageNumber = Math.max(1, parseInt(page) || 1);
|
||||||
const pageNumber = Math.max(1, parseInt(req.query.pageNumber) || 1);
|
const pageSize = Math.max(1, parseInt(limit) || 5);
|
||||||
const pageSize = Math.max(1, parseInt(req.query.pageSize) || 10);
|
|
||||||
|
|
||||||
// Count total songs based on the query
|
const pipeline = [
|
||||||
const totalSongs = await Song.countDocuments(query);
|
{ $match: matchStage },
|
||||||
const totalPages = Math.ceil(totalSongs / pageSize);
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'categories',
|
||||||
|
localField: 'categoryId',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'category'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'albums',
|
||||||
|
localField: 'albumId',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'album'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'subcategories',
|
||||||
|
localField: 'subcategoryId',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'subcategory'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'artists',
|
||||||
|
localField: 'artistId',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'artist'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
title: 1,
|
||||||
|
category: { $arrayElemAt: ['$category.name', 0] },
|
||||||
|
subcategory: { $arrayElemAt: ['$subcategory.SubCategoriesName', 0] },
|
||||||
|
artist: { $arrayElemAt: ['$artist.ArtistName', 0] },
|
||||||
|
album: { $arrayElemAt: ['$album.albumName', 0] },
|
||||||
|
status: '$status'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ $sort: { title: 1 } },
|
||||||
|
{ $skip: (pageNumber - 1) * pageSize },
|
||||||
|
{ $limit: pageSize }
|
||||||
|
];
|
||||||
|
|
||||||
// Find songs based on the query and pagination
|
const totalCount = await Song.countDocuments(matchStage);
|
||||||
const songs = await Song.find(query)
|
const totalPages = Math.ceil(totalCount / pageSize);
|
||||||
.populate({ path: 'categoryId', select: 'name' })
|
|
||||||
.populate({ path: 'albumId', select: 'albumName' })
|
|
||||||
.populate({ path: 'subcategoryId', select: 'SubCategoriesName' })
|
|
||||||
.populate({ path: 'artistId', select: 'ArtistName' })
|
|
||||||
.sort({ title: 1 })
|
|
||||||
.skip((pageNumber - 1) * pageSize)
|
|
||||||
.limit(pageSize);
|
|
||||||
|
|
||||||
// Check if songs are found
|
const songs = await Song.aggregate(pipeline);
|
||||||
if (songs.length === 0) {
|
|
||||||
return res.status(404).json({ error_code: 404, message: 'Songs not found' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return songs along with pagination details
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
error_code: 200,
|
error_code: 200,
|
||||||
message: 'Songs retrieved successfully',
|
message: 'Songs retrieved successfully',
|
||||||
songs,
|
songs,
|
||||||
|
// page:pageNumber,
|
||||||
|
// limit:pageSize,
|
||||||
|
total_count:totalCount,
|
||||||
total_pages: totalPages,
|
total_pages: totalPages,
|
||||||
current_page: pageNumber
|
current_page: pageNumber
|
||||||
});
|
});
|
||||||
|
@ -216,6 +625,46 @@ const getAllSongs = async (req, res) => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// const getAllSongs = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// const songs = await Song.find()
|
||||||
|
// .populate('languageId', 'name')
|
||||||
|
// .populate('artistId', 'ArtistName')
|
||||||
|
// .select('title musicLink trackerID lyrics coverArtImage');
|
||||||
|
|
||||||
|
// if (!songs || songs.length === 0) {
|
||||||
|
// return res.status(404).json({ error_code: 404, message: 'Songs not found' });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const songData = songs.map(song => {
|
||||||
|
// const { languageId, artistId, musicLink, trackerID, lyrics, coverArtImage } = song;
|
||||||
|
// const languageName = languageId ? languageId.name : null;
|
||||||
|
// const artistNames = artistId ? artistId.map(artist => artist.ArtistName) : null;
|
||||||
|
// const imageUrl = coverArtImage ? coverArtImage.imageUrl : null;
|
||||||
|
|
||||||
|
// return {
|
||||||
|
// languageName: languageName,
|
||||||
|
// artistNames: artistNames,
|
||||||
|
// musicLink: musicLink || null,
|
||||||
|
// trackerID: trackerID || null,
|
||||||
|
// lyrics: lyrics || null,
|
||||||
|
// imageUrl: imageUrl
|
||||||
|
// };
|
||||||
|
// });
|
||||||
|
|
||||||
|
// return res.status(200).json({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'Songs retrieved successfully',
|
||||||
|
// songs: songData
|
||||||
|
// });
|
||||||
|
// } catch (err) {
|
||||||
|
// console.error('Error inside getAllSongs:', err);
|
||||||
|
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|
|
@ -408,69 +408,30 @@ const changeSubCategoryStatus = async (req, res) => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// const getCategories = async (req, res) => {
|
const getCategories = async (req, res) => {
|
||||||
// try {
|
|
||||||
// const { CategoriesId } = req.params;
|
|
||||||
|
|
||||||
|
|
||||||
// const categories = await SubCategories.find({ CategoriesId: CategoriesId });
|
|
||||||
// console.log("🚀 ~ getCategories ~ categories:", categories)
|
|
||||||
// if (!categories || categories.length === 0) {
|
|
||||||
// return res.status(400).send({
|
|
||||||
// error_code: 400,
|
|
||||||
// message: 'Categories not found for the given category ID'
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Return the found categories
|
|
||||||
// res.status(200).json({
|
|
||||||
// error_code: 200,
|
|
||||||
// message: 'Categories retrieved successfully',
|
|
||||||
// categories: categories
|
|
||||||
// });
|
|
||||||
|
|
||||||
// } catch (err) {
|
|
||||||
// console.error('Error inside getCategories', err);
|
|
||||||
// res.status(500).send({
|
|
||||||
// error_code: 500,
|
|
||||||
// message: 'Internal Server Error'
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
|
|
||||||
// ------------------------------------------------
|
|
||||||
|
|
||||||
const getSubCategoriesfromCategory = async (req, res) => {
|
|
||||||
try {
|
try {
|
||||||
const { CategoriesId } = req.params;
|
const { CategoriesId } = req.params;
|
||||||
|
|
||||||
const categories = await SubCategories.find({ CategoriesId: CategoriesId });
|
|
||||||
|
|
||||||
|
const categories = await SubCategories.find({ CategoriesId: CategoriesId });
|
||||||
|
console.log("🚀 ~ getCategories ~ categories:", categories)
|
||||||
if (!categories || categories.length === 0) {
|
if (!categories || categories.length === 0) {
|
||||||
return res.status(400).json({
|
return res.status(400).send({
|
||||||
error_code: 400,
|
error_code: 400,
|
||||||
message: 'Categories not found for the given category ID'
|
message: 'Categories not found for the given category ID'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const categoriesWithImageUrl = categories.map(category => ({
|
// Return the found categories
|
||||||
_id: category._id,
|
|
||||||
SubCategoriesName: category.SubCategoriesName,
|
|
||||||
imageUrl: category.image ? category.image.imageUrl : null,
|
|
||||||
status: category.status,
|
|
||||||
CategoriesId: category.CategoriesId,
|
|
||||||
categoryName: category.categoryName
|
|
||||||
}));
|
|
||||||
|
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
error_code: 200,
|
error_code: 200,
|
||||||
message: 'Categories retrieved successfully',
|
message: 'Categories retrieved successfully',
|
||||||
categories: categoriesWithImageUrl
|
categories: categories
|
||||||
});
|
});
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error inside getCategories', err);
|
console.error('Error inside getCategories', err);
|
||||||
res.status(500).json({
|
res.status(500).send({
|
||||||
error_code: 500,
|
error_code: 500,
|
||||||
message: 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
});
|
});
|
||||||
|
@ -479,6 +440,45 @@ const getSubCategoriesfromCategory = async (req, res) => {
|
||||||
|
|
||||||
// ------------------------------------------------
|
// ------------------------------------------------
|
||||||
|
|
||||||
|
// const getSubCategoriesfromCategory = async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// const { CategoriesId } = req.params;
|
||||||
|
|
||||||
|
// const categories = await SubCategories.find({ CategoriesId: CategoriesId });
|
||||||
|
|
||||||
|
// if (!categories || categories.length === 0) {
|
||||||
|
// return res.status(400).json({
|
||||||
|
// error_code: 400,
|
||||||
|
// message: 'Categories not found for the given category ID'
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const categoriesWithImageUrl = categories.map(category => ({
|
||||||
|
// _id: category._id,
|
||||||
|
// SubCategoriesName: category.SubCategoriesName,
|
||||||
|
// imageUrl: category.image ? category.image.imageUrl : null,
|
||||||
|
// status: category.status,
|
||||||
|
// CategoriesId: category.CategoriesId,
|
||||||
|
// categoryName: category.categoryName
|
||||||
|
// }));
|
||||||
|
|
||||||
|
// res.status(200).json({
|
||||||
|
// error_code: 200,
|
||||||
|
// message: 'Categories retrieved successfully',
|
||||||
|
// categories: categoriesWithImageUrl
|
||||||
|
// });
|
||||||
|
|
||||||
|
// } catch (err) {
|
||||||
|
// console.error('Error inside getCategories', err);
|
||||||
|
// res.status(500).json({
|
||||||
|
// error_code: 500,
|
||||||
|
// message: 'Internal Server Error'
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
|
// ------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
@ -488,6 +488,6 @@ module.exports = {
|
||||||
getSubCategories,
|
getSubCategories,
|
||||||
deleteMany,
|
deleteMany,
|
||||||
changeSubCategoryStatus,
|
changeSubCategoryStatus,
|
||||||
getSubCategoriesfromCategory
|
getCategories
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
const User = require('../models/user.model');
|
// const User = require('../models/user.model');
|
||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const authConfig = require('../configs/auth.config');
|
const authConfig = require('../configs/auth.config');
|
||||||
const bcrypt = require('bcryptjs');
|
const bcrypt = require('bcryptjs');
|
||||||
|
@ -6,48 +6,187 @@ const constant = require('../util/constant');
|
||||||
const Artist = require('../models/artist.model');
|
const Artist = require('../models/artist.model');
|
||||||
const Reward = require('../models/Reward.model');
|
const Reward = require('../models/Reward.model');
|
||||||
const Song = require('../models/song.model');
|
const Song = require('../models/song.model');
|
||||||
|
const axios = require('axios');
|
||||||
|
const { User } = require('../models/user.model');
|
||||||
|
const { validationResult } = require('express-validator');
|
||||||
|
const nodemailer = require('nodemailer');
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
const sendOTPByEmail = async (email, otp) => {
|
||||||
|
try {
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
service: 'gmail', // e.g., 'Gmail'
|
||||||
|
auth: {
|
||||||
|
user: 'ay2087355@gmail.com',
|
||||||
|
pass: 'mqqqnoutaukxenlh'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Send OTP email
|
||||||
|
await transporter.sendMail({
|
||||||
|
from: 'checkdemo02@gmail.com',
|
||||||
|
to: email,
|
||||||
|
subject: 'Your OTP Code',
|
||||||
|
text: `Your OTP code is: ${otp}`
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('OTP email sent successfully');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error sending OTP email:', error);
|
||||||
|
throw new Error('Failed to send OTP email');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const userRegister = async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Check if the email already exists
|
||||||
|
const existingUser = await User.findOne({ email: req.body.email });
|
||||||
|
console.log("🚀 ~ userRegister ~ existingUser:", existingUser)
|
||||||
|
if (existingUser) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'Email already exists'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate OTP
|
||||||
|
const otp = Math.floor(10000 + Math.random() * 90000);
|
||||||
|
|
||||||
|
// Create user object with hashed password
|
||||||
|
const user = await User.create({
|
||||||
|
email: req.body.email,
|
||||||
|
password: bcrypt.hashSync(req.body.password, 8),
|
||||||
|
registerWith: constant.registerWith.Email,
|
||||||
|
otp: otp,
|
||||||
|
userName: req.body.userName,
|
||||||
|
userType: constant.userTypes.customer
|
||||||
|
});
|
||||||
|
console.log("🚀 ~ userRegister ~ user:", user)
|
||||||
|
|
||||||
|
// Send OTP email
|
||||||
|
await sendOTPByEmail(user.email, otp);
|
||||||
|
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Success',
|
||||||
|
user: user
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error in user registration:', err);
|
||||||
|
return res.status(500).json({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Failed'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//otp verify
|
||||||
|
|
||||||
|
const verifyOTP = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { email, otp } = req.body;
|
||||||
|
const user = await User.findOne({ email });
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.otp !== otp) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'Incorrect OTP'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
user.otpVerified = true;
|
||||||
|
await user.save();
|
||||||
|
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'OTP verified successfully',
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in verify OTP:', error);
|
||||||
|
return res.status(500).json({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Failed'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const createGoogle = async (req, res) => {
|
const createGoogle = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
// Validate request body
|
||||||
let user = await User.findOne({ email: req.body.email });
|
const errors = validationResult(req);
|
||||||
var flag = 0;
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({ errors: errors.array() });
|
||||||
if (!user) {
|
|
||||||
let obj = {
|
|
||||||
email: req.body.email,
|
|
||||||
registerWith: constant.registerWith.google
|
|
||||||
}
|
|
||||||
user = await User.create(obj);
|
|
||||||
flag = 1
|
|
||||||
|
|
||||||
}
|
}
|
||||||
if (user.registerWith != constant.registerWith.google) {
|
|
||||||
return res.status(400).send({
|
// Fetch user data from Google API using access token
|
||||||
error_code : 400,
|
const response = await axios.get(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${req.body.accessToken}`);
|
||||||
message: "Can't login Through google"
|
const userData = response.data;
|
||||||
|
|
||||||
|
// Check if the user with this Google ID already exists
|
||||||
|
let user = await User.findOne({ googleId: userData.id });
|
||||||
|
|
||||||
|
// If user with Google ID doesn't exist, check by email
|
||||||
|
if (!user) {
|
||||||
|
user = await User.findOne({ email: userData.email });
|
||||||
|
}
|
||||||
|
|
||||||
|
// If user exists, generate token and return response
|
||||||
|
if (user) {
|
||||||
|
const token = jwt.sign({ id: user._id, userType: user.userType }, process.env.JWT_SECRET, { expiresIn: '1h' });
|
||||||
|
return res.status(200).json({
|
||||||
|
_id: user._id,
|
||||||
|
email: user.email,
|
||||||
|
token: token,
|
||||||
|
userType: user.userType,
|
||||||
|
status: user.status,
|
||||||
|
message: 'User logged in successfully'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let str = flag ? 'User Got Created' : 'User was already Created';
|
|
||||||
|
|
||||||
const token = jwt.sign({ id: user._id }, authConfig.secretKey, {
|
// If user doesn't exist, create a new user
|
||||||
expiresIn: 600000
|
const newUser = await User.create({
|
||||||
|
email: userData.email,
|
||||||
|
name: userData.name,
|
||||||
|
profilePic: userData.picture,
|
||||||
|
authenticationType: "GOOGLE",
|
||||||
|
googleId: userData.id,
|
||||||
});
|
});
|
||||||
return res.status(201).send({
|
|
||||||
error_code : 200,
|
|
||||||
message: str,
|
|
||||||
acessToken: token
|
|
||||||
})
|
|
||||||
} catch (err) {
|
|
||||||
console.log(err);
|
|
||||||
return res.status(500).send({
|
|
||||||
error_code : 500,
|
|
||||||
message: 'Error in creating user'
|
|
||||||
})
|
|
||||||
|
|
||||||
|
// Generate token for the new user
|
||||||
|
const token = jwt.sign({ id: newUser._id, userType: newUser.userType }, process.env.JWT_SECRET, { expiresIn: '1h' });
|
||||||
|
|
||||||
|
// Send response with user data
|
||||||
|
return res.status(201).json({
|
||||||
|
_id: newUser._id,
|
||||||
|
email: newUser.email,
|
||||||
|
token: token,
|
||||||
|
userType: newUser.userType,
|
||||||
|
authenticationType: "GOOGLE",
|
||||||
|
status: newUser.status,
|
||||||
|
message: 'New user created and logged in successfully'
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Handle errors
|
||||||
|
console.error('Error inside createGoogle:', error);
|
||||||
|
return res.status(500).json({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Internal Server Error'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const update = async (req, res) => {
|
const update = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
let id = req.params.id;
|
let id = req.params.id;
|
||||||
|
@ -71,7 +210,7 @@ const update = async (req, res) => {
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
return res.status(401).send({
|
return res.status(401).send({
|
||||||
error_code : 400,
|
error_code: 400,
|
||||||
message: 'status can only be updated by admin'
|
message: 'status can only be updated by admin'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -84,13 +223,13 @@ const update = async (req, res) => {
|
||||||
await user.updateOne(obj)
|
await user.updateOne(obj)
|
||||||
await user.save();
|
await user.save();
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message: "User updated Successssssfully"
|
message: "User updated Successssssfully"
|
||||||
})
|
})
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
res.status(500).send({
|
res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message: 'Error in update controller '
|
message: 'Error in update controller '
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -126,14 +265,14 @@ const passUpCreate = async (req, res) => {
|
||||||
const user = await User.findOneAndUpdate({ email: email }, { $set: obj });
|
const user = await User.findOneAndUpdate({ email: email }, { $set: obj });
|
||||||
user.save();
|
user.save();
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message: `Temporary Password is ${TempPassword} for this ${email}`
|
message: `Temporary Password is ${TempPassword} for this ${email}`
|
||||||
})
|
})
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message: 'Error in passUpCreate'
|
message: 'Error in passUpCreate'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -155,7 +294,7 @@ const createFacebook = async (req, res) => {
|
||||||
}
|
}
|
||||||
if (user.registerWith != constant.registerWith.facebook) {
|
if (user.registerWith != constant.registerWith.facebook) {
|
||||||
return res.status(400).send({
|
return res.status(400).send({
|
||||||
error_code : 400,
|
error_code: 400,
|
||||||
message: "Can't login Through facebook"
|
message: "Can't login Through facebook"
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -166,7 +305,7 @@ const createFacebook = async (req, res) => {
|
||||||
expiresIn: 600000
|
expiresIn: 600000
|
||||||
});
|
});
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message: str,
|
message: str,
|
||||||
acessToken: token
|
acessToken: token
|
||||||
})
|
})
|
||||||
|
@ -176,7 +315,7 @@ const createFacebook = async (req, res) => {
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message: 'Error in creating user'
|
message: 'Error in creating user'
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -189,7 +328,7 @@ const deleteUser = async (req, res) => {
|
||||||
|
|
||||||
await User.deleteOne({ _id: id });
|
await User.deleteOne({ _id: id });
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message: 'User Deleted succefully'
|
message: 'User Deleted succefully'
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -198,7 +337,7 @@ const deleteUser = async (req, res) => {
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.log('Error inside delete User controller', err);
|
console.log('Error inside delete User controller', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message: 'internal server error'
|
message: 'internal server error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -212,7 +351,7 @@ const getUserPlaylist = async (req, res) => {
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log('Error inside getUserPlaylist Controller', err);
|
console.log('Error inside getUserPlaylist Controller', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message: 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -231,7 +370,7 @@ const favrioteSong = async (req, res) => {
|
||||||
});
|
});
|
||||||
await user.save();
|
await user.save();
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message: 'Song got removed from favrioteSong'
|
message: 'Song got removed from favrioteSong'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -240,14 +379,14 @@ const favrioteSong = async (req, res) => {
|
||||||
await user.save();
|
await user.save();
|
||||||
|
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message: 'Song got added to favrioteSong'
|
message: 'Song got added to favrioteSong'
|
||||||
})
|
})
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log('Error inside favrioteSong Controller', err);
|
console.log('Error inside favrioteSong Controller', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message: 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -262,7 +401,7 @@ const getfavrioteSongs = async (req, res) => {
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log('Error inside getFavrioteSong Controller', err);
|
console.log('Error inside getFavrioteSong Controller', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message: 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -273,33 +412,33 @@ const getfavrioteSongs = async (req, res) => {
|
||||||
|
|
||||||
const PlayedSong = async (req, res) => {
|
const PlayedSong = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
let key = req.params.id;
|
let key = req.params.id;
|
||||||
let userId = req.userId;
|
let userId = req.userId;
|
||||||
const user = await User.findById(userId);
|
const user = await User.findById(userId);
|
||||||
|
|
||||||
|
|
||||||
if (user.mostPlayedSongs[key]) {
|
if (user.mostPlayedSongs[key]) {
|
||||||
const updatedObj = {$set : {['mostPlayedSongs.'+key]:(++user.mostPlayedSongs[key])}}
|
const updatedObj = { $set: { ['mostPlayedSongs.' + key]: (++user.mostPlayedSongs[key]) } }
|
||||||
await User.findByIdAndUpdate(userId,updatedObj);
|
await User.findByIdAndUpdate(userId, updatedObj);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
else {
|
else {
|
||||||
const updatedObj = {$set:{['mostPlayedSongs.'+key]:1 }}
|
const updatedObj = { $set: { ['mostPlayedSongs.' + key]: 1 } }
|
||||||
console.log('not hello')
|
console.log('not hello')
|
||||||
await User.findByIdAndUpdate(userId,updatedObj)
|
await User.findByIdAndUpdate(userId, updatedObj)
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
error_code : 200,
|
error_code: 200,
|
||||||
message: 'Song is Played '
|
message: 'Song is Played '
|
||||||
})
|
})
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log('Error inside playedSong', err);
|
console.log('Error inside playedSong', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message: 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -310,7 +449,7 @@ const getmostPlayedSong = async (req, res) => {
|
||||||
const user = await User.findById(req.userId)
|
const user = await User.findById(req.userId)
|
||||||
console.log(user.mostPlayedSongs);
|
console.log(user.mostPlayedSongs);
|
||||||
|
|
||||||
// Convert the object to an array of key-value pairs
|
// Convert the object to an array of key-value pairs
|
||||||
const objEntries = Object.entries(user.mostPlayedSongs);
|
const objEntries = Object.entries(user.mostPlayedSongs);
|
||||||
|
|
||||||
// Sort the Array
|
// Sort the Array
|
||||||
|
@ -318,51 +457,51 @@ const getmostPlayedSong = async (req, res) => {
|
||||||
|
|
||||||
// Convert the sorted array back to an object
|
// Convert the sorted array back to an object
|
||||||
const sortedObj = Object.fromEntries(objEntries);
|
const sortedObj = Object.fromEntries(objEntries);
|
||||||
|
|
||||||
return res.status(201).send(sortedObj);
|
return res.status(201).send(sortedObj);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
||||||
|
|
||||||
console.log('Error inside mostPlayedSong', err);
|
console.log('Error inside mostPlayedSong', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message: 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const followingArtist = async(req,res) => {
|
const followingArtist = async (req, res) => {
|
||||||
try{
|
try {
|
||||||
const artistId = req.params.id;
|
const artistId = req.params.id;
|
||||||
const userId = req.userId;
|
const userId = req.userId;
|
||||||
const user = await User.findById(userId);
|
const user = await User.findById(userId);
|
||||||
const artist = await Artist.findById(artistId);
|
const artist = await Artist.findById(artistId);
|
||||||
for(let i=0;i<user.following.length;i++){
|
for (let i = 0; i < user.following.length; i++) {
|
||||||
if(user.following[i]==artistId) {
|
if (user.following[i] == artistId) {
|
||||||
user.following.pull(artistId);
|
user.following.pull(artistId);
|
||||||
await user.save();
|
await user.save();
|
||||||
artist.followers.pull(userId);
|
artist.followers.pull(userId);
|
||||||
await artist.save();
|
await artist.save();
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
message : `You Unfollowed ${artist.name}`
|
message: `You Unfollowed ${artist.name}`
|
||||||
})
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
user.following.push(artistId);
|
||||||
user.following.push(artistId);
|
await user.save();
|
||||||
await user.save();
|
artist.followers.push(userId);
|
||||||
artist.followers.push(userId);
|
await artist.save();
|
||||||
await artist.save();
|
return res.status(200).send({
|
||||||
return res.status(200).send({
|
error_code: 200,
|
||||||
error_code : 200,
|
message: `you followed ${artist.name}`
|
||||||
message : `you followed ${artist.name}`
|
})
|
||||||
})
|
|
||||||
|
} catch (err) {
|
||||||
}catch(err){
|
console.log('Error inside following Controller', err);
|
||||||
console.log('Error inside following Controller',err);
|
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message : 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -375,70 +514,70 @@ const followingArtist = async(req,res) => {
|
||||||
|
|
||||||
|
|
||||||
// Function to evaluate word alignment accuracy and timing accuracy
|
// Function to evaluate word alignment accuracy and timing accuracy
|
||||||
const evaluateAccuracy= async(req, res) => {
|
const evaluateAccuracy = async (req, res) => {
|
||||||
try{
|
try {
|
||||||
const song = await Song.findById(req.params.id);
|
const song = await Song.findById(req.params.id);
|
||||||
const recognizedLyrics = req.recognizedLyrics;
|
const recognizedLyrics = req.recognizedLyrics;
|
||||||
const originalLyrics = song.lyricsTimeStamp;
|
const originalLyrics = song.lyricsTimeStamp;
|
||||||
const wordAlignmentAccuracy = constant.calculateWordAlignmentAccuracy(recognizedLyrics, originalLyrics);
|
const wordAlignmentAccuracy = constant.calculateWordAlignmentAccuracy(recognizedLyrics, originalLyrics);
|
||||||
const timingAccuracy = constant.calculateTimingAccuracy(recognizedLyrics, originalLyrics);
|
const timingAccuracy = constant.calculateTimingAccuracy(recognizedLyrics, originalLyrics);
|
||||||
const totalAccuracy = (wordAlignmentAccuracy.toFixed(2) + timingAccuracy.toFixed(2))/2;
|
const totalAccuracy = (wordAlignmentAccuracy.toFixed(2) + timingAccuracy.toFixed(2)) / 2;
|
||||||
console.log(totalAccuracy);
|
console.log(totalAccuracy);
|
||||||
var reward ;
|
var reward;
|
||||||
switch(totalAccuracy){
|
switch (totalAccuracy) {
|
||||||
case(totalAccuracy>90) :
|
case (totalAccuracy > 90):
|
||||||
reward = 'A+';
|
reward = 'A+';
|
||||||
break ;
|
break;
|
||||||
case(totalAccuracy>80) :
|
case (totalAccuracy > 80):
|
||||||
reward = 'A'
|
reward = 'A'
|
||||||
break;
|
break;
|
||||||
case(totalAccuracy>70) :
|
case (totalAccuracy > 70):
|
||||||
reward = 'B+'
|
reward = 'B+'
|
||||||
break;
|
break;
|
||||||
case(totalAccuracy>60) :
|
case (totalAccuracy > 60):
|
||||||
reward = 'B'
|
reward = 'B'
|
||||||
break;
|
break;
|
||||||
case(totalAccuracy>50) :
|
case (totalAccuracy > 50):
|
||||||
reward = 'C+'
|
reward = 'C+'
|
||||||
break;
|
break;
|
||||||
case(totalAccuracy>40) :
|
case (totalAccuracy > 40):
|
||||||
reward = 'C'
|
reward = 'C'
|
||||||
break ;
|
break;
|
||||||
case(totalAccuracy<40) :
|
case (totalAccuracy < 40):
|
||||||
reward = 'F'
|
reward = 'F'
|
||||||
break;
|
break;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const reward_score = await Reward.find({score : reward});
|
|
||||||
const user = await User.findById(req.userId);
|
|
||||||
user.score += reward_score.reward;
|
|
||||||
await user.save();
|
|
||||||
console.log(user);
|
|
||||||
return res.status(201).send({
|
|
||||||
error_code : 200,
|
|
||||||
Score : reward
|
|
||||||
})
|
|
||||||
|
|
||||||
}catch(err){
|
const reward_score = await Reward.find({ score: reward });
|
||||||
console.log('Error inside EvaluateAccuracy Controller',err);
|
const user = await User.findById(req.userId);
|
||||||
return res.status(500).send({
|
user.score += reward_score.reward;
|
||||||
error_code : 500,
|
await user.save();
|
||||||
message : 'Internal Server Error'
|
console.log(user);
|
||||||
})
|
return res.status(201).send({
|
||||||
}
|
error_code: 200,
|
||||||
|
Score: reward
|
||||||
|
})
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.log('Error inside EvaluateAccuracy Controller', err);
|
||||||
|
return res.status(500).send({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Internal Server Error'
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const ranking = async(req,res) => {
|
const ranking = async (req, res) => {
|
||||||
try{
|
try {
|
||||||
const ranking = await User.find({}).sort({score : -1}).limit(5);
|
const ranking = await User.find({}).sort({ score: -1 }).limit(5);
|
||||||
return res.status(201).send(ranking);
|
return res.status(201).send(ranking);
|
||||||
|
|
||||||
}catch(err){
|
} catch (err) {
|
||||||
console.log('Error inside Ranking Controller',err);
|
console.log('Error inside Ranking Controller', err);
|
||||||
return res.status(500).send({
|
return res.status(500).send({
|
||||||
error_code : 500,
|
error_code: 500,
|
||||||
message : 'Internal Server Error'
|
message: 'Internal Server Error'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -480,9 +619,162 @@ const changeUserStatus = async (req, res) => {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const usergetAllSongs =async(req,res)=>{
|
||||||
|
try {
|
||||||
|
const song = await Song.find({status: 'Active'});
|
||||||
|
return res.status(200).send(song);
|
||||||
|
|
||||||
|
|
||||||
|
}catch (err) {
|
||||||
|
console.log('Error inside changeStatus controller', err);
|
||||||
|
return res.status(500).send({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Internal server error.'
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const newRelease = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const fiveDaysAgo = new Date();
|
||||||
|
fiveDaysAgo.setDate(fiveDaysAgo.getDate() - 3);
|
||||||
|
const songs = await Song.find({
|
||||||
|
status: 'activate',
|
||||||
|
createdAt: { $gte: fiveDaysAgo }
|
||||||
|
});
|
||||||
|
|
||||||
|
return res.status(200).send({error_code:200,message:'new realese songs',song:songs});
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.log('Error inside newRelease controller', err);
|
||||||
|
return res.status(500).send({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Internal server error.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const homeData = async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Pipeline to aggregate songs with category name, artist names, and image URL
|
||||||
|
const pipeline = [
|
||||||
|
{
|
||||||
|
$match: { status: 'activate' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'categories',
|
||||||
|
localField: 'categoryId',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'category'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'artists',
|
||||||
|
localField: 'artistId',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'artists'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: { categoryId: '$categoryId', categoryName: '$category.name' },
|
||||||
|
songs: {
|
||||||
|
$push: {
|
||||||
|
_id: '$_id',
|
||||||
|
title: '$title',
|
||||||
|
artistNames: '$artists.ArtistName',
|
||||||
|
imageUrl: '$coverArtImage.imageUrl'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
_id: 0,
|
||||||
|
categoryName: '$_id.categoryName',
|
||||||
|
songs: {
|
||||||
|
$map: {
|
||||||
|
input: '$songs',
|
||||||
|
as: 'song',
|
||||||
|
in: {
|
||||||
|
_id: '$$song._id',
|
||||||
|
title: '$$song.title',
|
||||||
|
artistNames: '$$song.artistNames',
|
||||||
|
imageUrl: '$$song.imageUrl'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
const categoriesWithSongs = await Song.aggregate(pipeline);
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Songs grouped by category retrieved successfully',
|
||||||
|
categories: categoriesWithSongs
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
// Log and handle errors
|
||||||
|
console.error('Error inside homeData:', err);
|
||||||
|
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const artistData = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const pipeline = [
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'songs',
|
||||||
|
localField: '_id',
|
||||||
|
foreignField: 'artistId',
|
||||||
|
as: 'songs'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
_id: 1,
|
||||||
|
ArtistName: 1,
|
||||||
|
songs: {
|
||||||
|
$map: {
|
||||||
|
input: '$songs',
|
||||||
|
as: 'song',
|
||||||
|
in: {
|
||||||
|
_id: '$$song._id',
|
||||||
|
title: '$$song.title',
|
||||||
|
status: '$$song.status',
|
||||||
|
imageUrl: '$$song.coverArtImage.imageUrl'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
// Execute aggregation pipeline
|
||||||
|
const artistsWithSongs = await Artist.aggregate(pipeline);
|
||||||
|
|
||||||
|
// Return response
|
||||||
|
return res.status(200).json({
|
||||||
|
error_code: 200,
|
||||||
|
message: 'Artist data with songs retrieved successfully',
|
||||||
|
artists: artistsWithSongs
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Log and handle errors
|
||||||
|
console.error('Error inside artistData:', error);
|
||||||
|
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
userRegister,
|
||||||
|
verifyOTP,
|
||||||
createGoogle,
|
createGoogle,
|
||||||
createFacebook,
|
createFacebook,
|
||||||
update,
|
update,
|
||||||
|
@ -496,5 +788,8 @@ module.exports = {
|
||||||
followingArtist,
|
followingArtist,
|
||||||
evaluateAccuracy,
|
evaluateAccuracy,
|
||||||
ranking,
|
ranking,
|
||||||
changeUserStatus
|
changeUserStatus,usergetAllSongs,
|
||||||
|
newRelease,
|
||||||
|
homeData,
|
||||||
|
artistData
|
||||||
};
|
};
|
|
@ -1,4 +1,4 @@
|
||||||
const User = require('../models/user.model');
|
const {User} = require('../models/user.model');
|
||||||
const constant = require('../util/constant')
|
const constant = require('../util/constant')
|
||||||
|
|
||||||
const isAdmin = async(req,res,next) => {
|
const isAdmin = async(req,res,next) => {
|
||||||
|
|
|
@ -1,42 +1,49 @@
|
||||||
const regex = require('../regex');
|
const regex = require('../regex');
|
||||||
const User = require('../../models/user.model')
|
const {User} = require('../../models/user.model')
|
||||||
|
const multer = require('multer');
|
||||||
|
|
||||||
const fieldCheck = async(req,res,next) => {
|
const fieldCheck = async (req, res, next) => {
|
||||||
try{
|
try {
|
||||||
if(!req.body.email){
|
|
||||||
return res.status(400).send({
|
|
||||||
error_code : 400,
|
|
||||||
message : 'Email not provided'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if(!req.body.password){
|
|
||||||
return res.status(400).send({
|
|
||||||
error_code : 400,
|
|
||||||
message : 'Password not provided'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if(!regex.emailRegex.test(req.body.email)){
|
|
||||||
return res.status(400).send({
|
|
||||||
error_code : 400,
|
|
||||||
message : 'Email format is Incorrect'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if(!regex.passRegex.test(req.body.password)){
|
|
||||||
return res.status(400).send({
|
|
||||||
error_code : 400,
|
|
||||||
message : 'Password format is Incorrect'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
next();
|
|
||||||
|
|
||||||
}catch(err){
|
if (!req.body.email || req.body.email.trim() === '') {
|
||||||
console.log('Error inside auth Middelware fieldCheck',err);
|
return res.status(400).json({
|
||||||
return res.status(500).send({
|
error_code: 400,
|
||||||
error_code : 500,
|
message: 'Email not provided or empty'
|
||||||
message : 'Internal Error'
|
});
|
||||||
})
|
}
|
||||||
|
|
||||||
|
if (!req.body.password || req.body.password.trim() === '') {
|
||||||
|
return res.status(400).json({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'Password not provided or empty'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!regex.emailRegex.test(req.body.email)) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'Email format is incorrect'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!regex.passRegex.test(req.body.password)) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error_code: 400,
|
||||||
|
message: 'Password format is incorrect'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error inside auth Middleware fieldCheck:', err);
|
||||||
|
return res.status(500).json({
|
||||||
|
error_code: 500,
|
||||||
|
message: 'Internal Server Error'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const uniqueEmail = async(req,res,next) => {
|
const uniqueEmail = async(req,res,next) => {
|
||||||
|
@ -61,6 +68,7 @@ const uniqueEmail = async(req,res,next) => {
|
||||||
|
|
||||||
const userCheckEmail = async (req,res,next) => {
|
const userCheckEmail = async (req,res,next) => {
|
||||||
try{
|
try{
|
||||||
|
|
||||||
const user = await User.findOne({email : req.body.email});
|
const user = await User.findOne({email : req.body.email});
|
||||||
if(!user){
|
if(!user){
|
||||||
return res.status(400).send({
|
return res.status(400).send({
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const User = require('../models/user.model');
|
const {User} = require('../models/user.model');
|
||||||
const authConfig = require('../configs/auth.config');
|
const authConfig = require('../configs/auth.config');
|
||||||
|
|
||||||
const verifyToken = (req,res,next)=>{
|
const verifyToken = (req,res,next)=>{
|
||||||
|
@ -23,6 +23,7 @@ const verifyToken = (req,res,next)=>{
|
||||||
console.log(decoded);
|
console.log(decoded);
|
||||||
req.userId = decoded.id;
|
req.userId = decoded.id;
|
||||||
const user = await User.findOne({_id:req.userId});
|
const user = await User.findOne({_id:req.userId});
|
||||||
|
console.log("🚀 ~ jwt.verify ~ user:", user)
|
||||||
if(!user){
|
if(!user){
|
||||||
return res.status(400).send({
|
return res.status(400).send({
|
||||||
error_code : 400,
|
error_code : 400,
|
||||||
|
|
|
@ -1,29 +1,29 @@
|
||||||
const mongoose = require('mongoose')
|
const mongoose = require('mongoose')
|
||||||
|
|
||||||
const idCheck = async(req,res,next)=>{
|
const idCheck = async (req, res, next) => {
|
||||||
try{
|
try {
|
||||||
if(!req.params.id)
|
console.log(req.params,"sjkhfjsfad");
|
||||||
{
|
if (!req.params._id) {
|
||||||
return res.status(401).send({
|
return res.status(400).json({
|
||||||
message : 'id not present'
|
message: 'ID not present'
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
let check = mongoose.isValidObjectId(req.params.id);
|
|
||||||
|
|
||||||
if(!check){
|
|
||||||
return res.status(400).send({
|
|
||||||
message : 'Not a valid Param id'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (!mongoose.isValidObjectId(req.params._id)) {
|
||||||
next()
|
return res.status(400).json({
|
||||||
}catch(err){
|
message: 'Not a valid ID'
|
||||||
return res.status(500).send({
|
});
|
||||||
message : 'Internal Server Error'
|
}
|
||||||
})
|
|
||||||
|
next();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error inside idCheck middleware:', err);
|
||||||
|
return res.status(500).json({
|
||||||
|
message: 'Internal Server Error'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
idCheck
|
idCheck
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
let nameRegex = /^[.a-zA-Z\s]+$/;
|
let nameRegex = /^[.a-zA-Z\s]+$/;
|
||||||
let phoneRegex = /^(\+91[\-\s]?)?[0]?(91)?[6789]\d{9}$/;
|
let phoneRegex = /^(\+91[\-\s]?)?[0]?(91)?[6789]\d{9}$/;
|
||||||
let emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
|
let emailRegex = /.+@.+\..+/;
|
||||||
let passRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$/;
|
let passRegex = /.{6,}/;
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|
|
@ -0,0 +1,16 @@
|
||||||
|
const multer = require('multer');
|
||||||
|
|
||||||
|
const storage = multer.diskStorage({
|
||||||
|
destination: function (req, file, cb) {
|
||||||
|
if (file.fieldname === 'coverArtImage' || file.fieldname === 'musicFile') {
|
||||||
|
cb(null, './uploads');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
filename: function (req, file, cb) {
|
||||||
|
cb(null, file.originalname);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const upload = multer({ storage: storage });
|
||||||
|
|
||||||
|
module.exports = upload.any(); // Use upload.any() method
|
|
@ -5,7 +5,6 @@ const mongoose = require('mongoose');
|
||||||
const artistSchema = new mongoose.Schema({
|
const artistSchema = new mongoose.Schema({
|
||||||
ArtistName: {
|
ArtistName: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true
|
|
||||||
},
|
},
|
||||||
image: {
|
image: {
|
||||||
fileName: String,
|
fileName: String,
|
||||||
|
|
|
@ -3,17 +3,14 @@ const mongoose = require('mongoose');
|
||||||
const categorySchema = new mongoose.Schema({
|
const categorySchema = new mongoose.Schema({
|
||||||
name: {
|
name: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true
|
|
||||||
},
|
},
|
||||||
image: {
|
image: {
|
||||||
fileName: {
|
fileName: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true
|
|
||||||
},
|
},
|
||||||
fileAddress: {
|
fileAddress: {
|
||||||
type: String,
|
type: String, }
|
||||||
required: true
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
imageUrl: { type: String },
|
imageUrl: { type: String },
|
||||||
status: {
|
status: {
|
||||||
|
|
|
@ -1,7 +1,10 @@
|
||||||
const mongoose = require('mongoose');
|
const mongoose = require('mongoose');
|
||||||
const constant = require('../util/notification.constant')
|
const constant = require('../util/notification.constant')
|
||||||
|
const Schema = mongoose.Schema;
|
||||||
|
|
||||||
const notificationSchema = new mongoose.Schema({
|
const notificationSchema = new mongoose.Schema({
|
||||||
|
|
||||||
|
userId: { type: Schema.Types.ObjectId, ref: 'User' },
|
||||||
sendTo: {
|
sendTo: {
|
||||||
type: [String],
|
type: [String],
|
||||||
enum: [constant.sendTo.toAll, constant.sendTo.host, constant.sendTo.specific],
|
enum: [constant.sendTo.toAll, constant.sendTo.host, constant.sendTo.specific],
|
||||||
|
@ -24,10 +27,10 @@ const notificationSchema = new mongoose.Schema({
|
||||||
type: String,
|
type: String,
|
||||||
required: true
|
required: true
|
||||||
},
|
},
|
||||||
recipients: {
|
// recipients: {
|
||||||
type: [mongoose.SchemaType.objectId],
|
// type: [mongoose.SchemaType.objectId],
|
||||||
default: []
|
// default: []
|
||||||
}
|
// }
|
||||||
}, { timestamps: true });
|
}, { timestamps: true });
|
||||||
|
|
||||||
module.exports = mongoose.model('Notification', notificationSchema);
|
module.exports = mongoose.model('Notification', notificationSchema);
|
|
@ -6,7 +6,10 @@ const songSchema = new Schema({
|
||||||
categoryId: { type: Schema.Types.ObjectId, ref: 'Category' },
|
categoryId: { type: Schema.Types.ObjectId, ref: 'Category' },
|
||||||
subcategoryId: { type: Schema.Types.ObjectId, ref: 'SubCategories' },
|
subcategoryId: { type: Schema.Types.ObjectId, ref: 'SubCategories' },
|
||||||
albumId: { type: Schema.Types.ObjectId, ref: 'Album' },
|
albumId: { type: Schema.Types.ObjectId, ref: 'Album' },
|
||||||
artistId: { type: Schema.Types.ObjectId, ref: 'Artist' },
|
artistId: [{
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
ref: 'Artist',
|
||||||
|
}],
|
||||||
title: String,
|
title: String,
|
||||||
musicLink: String,
|
musicLink: String,
|
||||||
trackerID: String,
|
trackerID: String,
|
||||||
|
@ -19,7 +22,8 @@ const songSchema = new Schema({
|
||||||
},
|
},
|
||||||
musicFile: {
|
musicFile: {
|
||||||
filename: String,
|
filename: String,
|
||||||
fileAddress: String
|
fileAddress: String,
|
||||||
|
url: String
|
||||||
},
|
},
|
||||||
status: {
|
status: {
|
||||||
type: String,
|
type: String,
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
const mongoose = require("mongoose");
|
const mongoose = require("mongoose");
|
||||||
|
const bcrypt = require('bcrypt');
|
||||||
const constant = require('../util/constant');
|
const constant = require('../util/constant');
|
||||||
|
|
||||||
const userSchema = new mongoose.Schema({
|
const userSchema = new mongoose.Schema({
|
||||||
|
@ -6,129 +7,122 @@ const userSchema = new mongoose.Schema({
|
||||||
type: String,
|
type: String,
|
||||||
unique: true,
|
unique: true,
|
||||||
default: function () {
|
default: function () {
|
||||||
let username = 'guest' + Math.floor(Math.random() * 10000);
|
return 'guest' + Math.floor(Math.random() * 10000);
|
||||||
return username;
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
image: {
|
image: {
|
||||||
|
fileName: String,
|
||||||
fileName: {
|
fileAddress: String
|
||||||
type: String,
|
|
||||||
},
|
|
||||||
fileAddress: {
|
|
||||||
type: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
},
|
},
|
||||||
|
deviceToken: { type: String, default: "" },
|
||||||
imageUrl:{
|
accessToken:{ type: String, default: "" },
|
||||||
type: String
|
deviceType: { type: String, default: "" },
|
||||||
},
|
imageUrl: String,
|
||||||
firstName:{
|
firstName: String,
|
||||||
type: String,
|
lastName: String,
|
||||||
// required: true
|
address: String,
|
||||||
},
|
mobileNo: Number,
|
||||||
lastName:{
|
|
||||||
type: String,
|
|
||||||
// required: true
|
|
||||||
|
|
||||||
},
|
|
||||||
|
|
||||||
address:{
|
|
||||||
|
|
||||||
type: String,
|
|
||||||
|
|
||||||
},
|
|
||||||
mobileNo:{
|
|
||||||
type: Number
|
|
||||||
|
|
||||||
},
|
|
||||||
|
|
||||||
email: {
|
email: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true,
|
// required: true,
|
||||||
lowercase: true, // it will covert the email into the lower case and then store in the db,
|
lowercase: true,
|
||||||
minLength: 10, // anything less than 10 will fail
|
|
||||||
unique: true
|
unique: true
|
||||||
|
|
||||||
},
|
},
|
||||||
password: {
|
password: {
|
||||||
type: String,
|
type: String,
|
||||||
|
// required: true
|
||||||
},
|
},
|
||||||
userTypes: {
|
userTypes: {
|
||||||
type: String,
|
type: String,
|
||||||
enum: [constant.userTypes.admin, constant.userTypes.customer],
|
enum: [constant.userTypes.admin, constant.userTypes.customer],
|
||||||
default: constant.userTypes.customer
|
default: constant.userTypes.customer
|
||||||
|
|
||||||
},
|
},
|
||||||
status: {
|
status: {
|
||||||
type: String,
|
type: String,
|
||||||
enum: ['Active', 'Deactive'],
|
enum: ['Active', 'Deactive'],
|
||||||
default: 'Active'
|
default: 'Active'
|
||||||
|
|
||||||
},
|
},
|
||||||
registerWith: {
|
registerWith: {
|
||||||
type: String,
|
type: String,
|
||||||
enum: [constant.registerWith.Email, constant.registerWith.google, constant.registerWith.facebook],
|
enum: [constant.registerWith.Email, constant.registerWith.google, constant.registerWith.facebook],
|
||||||
default: constant.registerWith.Email
|
default: constant.registerWith.Email
|
||||||
},
|
},
|
||||||
playlist: {
|
playlist: [{
|
||||||
type: [mongoose.Schema.Types.ObjectId],
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
ref: 'PlayList'
|
ref: 'PlayList'
|
||||||
},
|
}],
|
||||||
favrioteSongs: {
|
favoriteSongs: [{
|
||||||
type: [mongoose.Schema.Types.ObjectId],
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
ref: 'Song',
|
ref: 'Song'
|
||||||
},
|
}],
|
||||||
mostPlayedSongs: {
|
mostPlayedSongs: {
|
||||||
type: Object,
|
type: Object,
|
||||||
ref: 'Song',
|
|
||||||
default: {}
|
default: {}
|
||||||
},
|
},
|
||||||
following: {
|
following: [{
|
||||||
type: [mongoose.Schema.Types.ObjectId],
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
ref: 'Artist'
|
ref: 'Artist'
|
||||||
},
|
}],
|
||||||
score: {
|
score: {
|
||||||
type: Number,
|
type: Number,
|
||||||
default: 0
|
default: 0
|
||||||
},
|
},
|
||||||
otp : Number,
|
otp: Number,
|
||||||
|
otpVerifly:{
|
||||||
|
type: Boolean,
|
||||||
|
default: false
|
||||||
|
},
|
||||||
createdAt: {
|
createdAt: {
|
||||||
// I want to default to a new date
|
|
||||||
type: Date,
|
type: Date,
|
||||||
immutable: true, // This will ensure the createdAt column is never updated but once in the start
|
immutable: true,
|
||||||
default: () => {
|
default: Date.now
|
||||||
return Date.now();
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
updatedAt: {
|
updatedAt: {
|
||||||
type: Date,
|
type: Date,
|
||||||
default: () => {
|
default: Date.now
|
||||||
return Date.now();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
userSchema.pre('deleteOne', async function (next) {
|
userSchema.pre('deleteOne', async function (next) {
|
||||||
const userId = this.getFilter()['_id'];
|
const userId = this.getFilter()['_id'];
|
||||||
const Artist = require('../models/artist.model');
|
const Artist = require('../models/artist.model');
|
||||||
|
const artist = await Artist.find({ followers: userId });
|
||||||
|
|
||||||
const artist = await Artist.find({
|
const artistPromises = artist.map(async (artist) => {
|
||||||
followers: userId
|
|
||||||
})
|
|
||||||
|
|
||||||
const artistPromises = artist.map(artist => {
|
|
||||||
artist.followers.pull(userId);
|
artist.followers.pull(userId);
|
||||||
return artist.save();
|
await artist.save();
|
||||||
})
|
});
|
||||||
|
|
||||||
await Promise.all(artistPromises);
|
await Promise.all(artistPromises);
|
||||||
|
});
|
||||||
|
|
||||||
})
|
const User = mongoose.model("User", userSchema);
|
||||||
|
|
||||||
module.exports = mongoose.model("User", userSchema);
|
|
||||||
|
const findDefaultAdmin = async () => {
|
||||||
|
try {
|
||||||
|
const result = await User.findOne({ userTypes: constant.userTypes.admin });
|
||||||
|
if (!result) {
|
||||||
|
const obj = {
|
||||||
|
userTypes: constant.userTypes.admin,
|
||||||
|
name: "musicNFT",
|
||||||
|
mobileNumber: "7038415050",
|
||||||
|
userName:"admin",
|
||||||
|
email: "admin@email.com",
|
||||||
|
password: bcrypt.hashSync("Admin@1", 10),
|
||||||
|
address: "INDIA",
|
||||||
|
otpVerifly:true
|
||||||
|
};
|
||||||
|
const admin = await User.create(obj);
|
||||||
|
console.log("Default Admin Created 😇😉😄", admin);
|
||||||
|
} else {
|
||||||
|
console.log("Default Admin 😉😄");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error finding or creating default admin:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
findDefaultAdmin();
|
||||||
|
|
||||||
|
module.exports = { User };
|
||||||
|
|
|
@ -4,6 +4,39 @@
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
|
"node_modules/@mapbox/node-pre-gyp": {
|
||||||
|
"version": "1.0.11",
|
||||||
|
"resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
|
||||||
|
"integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"detect-libc": "^2.0.0",
|
||||||
|
"https-proxy-agent": "^5.0.0",
|
||||||
|
"make-dir": "^3.1.0",
|
||||||
|
"node-fetch": "^2.6.7",
|
||||||
|
"nopt": "^5.0.0",
|
||||||
|
"npmlog": "^5.0.1",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"semver": "^7.3.5",
|
||||||
|
"tar": "^6.1.11"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"node-pre-gyp": "bin/node-pre-gyp"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@mapbox/node-pre-gyp/node_modules/nopt": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"abbrev": "1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"nopt": "bin/nopt.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/node": {
|
"node_modules/@types/node": {
|
||||||
"version": "20.11.24",
|
"version": "20.11.24",
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.24.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.24.tgz",
|
||||||
|
@ -61,6 +94,46 @@
|
||||||
"url": "https://github.com/sponsors/wooorm"
|
"url": "https://github.com/sponsors/wooorm"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/agent-base": {
|
||||||
|
"version": "6.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
|
||||||
|
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"debug": "4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/agent-base/node_modules/debug": {
|
||||||
|
"version": "4.3.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
|
||||||
|
"integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"ms": "2.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"supports-color": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/agent-base/node_modules/ms": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
|
||||||
|
},
|
||||||
|
"node_modules/ansi-regex": {
|
||||||
|
"version": "5.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||||
|
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/anymatch": {
|
"node_modules/anymatch": {
|
||||||
"version": "3.1.3",
|
"version": "3.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
|
||||||
|
@ -89,24 +162,47 @@
|
||||||
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
|
||||||
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw=="
|
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw=="
|
||||||
},
|
},
|
||||||
|
"node_modules/aproba": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ=="
|
||||||
|
},
|
||||||
|
"node_modules/are-we-there-yet": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==",
|
||||||
|
"dependencies": {
|
||||||
|
"delegates": "^1.0.0",
|
||||||
|
"readable-stream": "^3.6.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/are-we-there-yet/node_modules/readable-stream": {
|
||||||
|
"version": "3.6.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
||||||
|
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||||
|
"dependencies": {
|
||||||
|
"inherits": "^2.0.3",
|
||||||
|
"string_decoder": "^1.1.1",
|
||||||
|
"util-deprecate": "^1.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/array-flatten": {
|
"node_modules/array-flatten": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
||||||
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
|
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
|
||||||
},
|
},
|
||||||
"node_modules/asynckit": {
|
|
||||||
"version": "0.4.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
|
||||||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
|
|
||||||
},
|
|
||||||
"node_modules/axios": {
|
"node_modules/axios": {
|
||||||
"version": "1.6.7",
|
"version": "0.21.4",
|
||||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz",
|
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
|
||||||
"integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==",
|
"integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"follow-redirects": "^1.15.4",
|
"follow-redirects": "^1.14.0"
|
||||||
"form-data": "^4.0.0",
|
|
||||||
"proxy-from-env": "^1.1.0"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/balanced-match": {
|
"node_modules/balanced-match": {
|
||||||
|
@ -114,6 +210,35 @@
|
||||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
|
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
|
||||||
},
|
},
|
||||||
|
"node_modules/basic-auth": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
|
||||||
|
"dependencies": {
|
||||||
|
"safe-buffer": "5.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/basic-auth/node_modules/safe-buffer": {
|
||||||
|
"version": "5.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||||
|
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
|
||||||
|
},
|
||||||
|
"node_modules/bcrypt": {
|
||||||
|
"version": "5.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz",
|
||||||
|
"integrity": "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@mapbox/node-pre-gyp": "^1.0.11",
|
||||||
|
"node-addon-api": "^5.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/bcryptjs": {
|
"node_modules/bcryptjs": {
|
||||||
"version": "2.4.3",
|
"version": "2.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",
|
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",
|
||||||
|
@ -248,15 +373,20 @@
|
||||||
"fsevents": "~2.3.2"
|
"fsevents": "~2.3.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/combined-stream": {
|
"node_modules/chownr": {
|
||||||
"version": "1.0.8",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
"resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
|
||||||
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
"integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
|
||||||
"dependencies": {
|
|
||||||
"delayed-stream": "~1.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 0.8"
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/color-support": {
|
||||||
|
"version": "1.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz",
|
||||||
|
"integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==",
|
||||||
|
"bin": {
|
||||||
|
"color-support": "bin.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/concat-map": {
|
"node_modules/concat-map": {
|
||||||
|
@ -278,6 +408,11 @@
|
||||||
"typedarray": "^0.0.6"
|
"typedarray": "^0.0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/console-control-strings": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="
|
||||||
|
},
|
||||||
"node_modules/content-disposition": {
|
"node_modules/content-disposition": {
|
||||||
"version": "0.5.4",
|
"version": "0.5.4",
|
||||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||||
|
@ -351,13 +486,10 @@
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/delayed-stream": {
|
"node_modules/delegates": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
|
||||||
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
"integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ=="
|
||||||
"engines": {
|
|
||||||
"node": ">=0.4.0"
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"node_modules/depd": {
|
"node_modules/depd": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
|
@ -376,6 +508,55 @@
|
||||||
"npm": "1.2.8000 || >= 1.4.16"
|
"npm": "1.2.8000 || >= 1.4.16"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/detect-libc": {
|
||||||
|
"version": "2.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz",
|
||||||
|
"integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/dicer": {
|
||||||
|
"version": "0.2.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/dicer/-/dicer-0.2.5.tgz",
|
||||||
|
"integrity": "sha512-FDvbtnq7dzlPz0wyYlOExifDEZcu8h+rErEXgfxqmLfRfC/kJidEFh4+effJRO3P0xmfqyPbSMG0LveNRfTKVg==",
|
||||||
|
"dependencies": {
|
||||||
|
"readable-stream": "1.1.x",
|
||||||
|
"streamsearch": "0.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/dicer/node_modules/isarray": {
|
||||||
|
"version": "0.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
|
||||||
|
"integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ=="
|
||||||
|
},
|
||||||
|
"node_modules/dicer/node_modules/readable-stream": {
|
||||||
|
"version": "1.1.14",
|
||||||
|
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
|
||||||
|
"integrity": "sha512-+MeVjFf4L44XUkhM1eYbD8fyEsxcV81pqMSR5gblfcLCHfZvbrqy4/qYHE+/R5HoBUT11WV5O08Cr1n3YXkWVQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"core-util-is": "~1.0.0",
|
||||||
|
"inherits": "~2.0.1",
|
||||||
|
"isarray": "0.0.1",
|
||||||
|
"string_decoder": "~0.10.x"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/dicer/node_modules/streamsearch": {
|
||||||
|
"version": "0.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-0.1.2.tgz",
|
||||||
|
"integrity": "sha512-jos8u++JKm0ARcSUTAZXOVC0mSox7Bhn6sBgty73P1f3JGf7yG2clTbBNHUdde/kdvP2FESam+vM6l8jBrNxHA==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/dicer/node_modules/string_decoder": {
|
||||||
|
"version": "0.10.31",
|
||||||
|
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
|
||||||
|
"integrity": "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ=="
|
||||||
|
},
|
||||||
"node_modules/dotenv": {
|
"node_modules/dotenv": {
|
||||||
"version": "16.3.1",
|
"version": "16.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",
|
||||||
|
@ -400,6 +581,11 @@
|
||||||
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
||||||
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="
|
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="
|
||||||
},
|
},
|
||||||
|
"node_modules/emoji-regex": {
|
||||||
|
"version": "8.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||||
|
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="
|
||||||
|
},
|
||||||
"node_modules/encodeurl": {
|
"node_modules/encodeurl": {
|
||||||
"version": "1.0.2",
|
"version": "1.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
|
||||||
|
@ -481,6 +667,29 @@
|
||||||
"node": ">= 0.10.0"
|
"node": ">= 0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/express-fileupload": {
|
||||||
|
"version": "1.5.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/express-fileupload/-/express-fileupload-1.5.0.tgz",
|
||||||
|
"integrity": "sha512-jSW3w9evqM37VWkEPkL2Ck5wUo2a8qa03MH+Ou/0ZSTpNlQFBvSLjU12k2nYcHhaMPv4JVvv6+Ac1OuLgUZb7w==",
|
||||||
|
"dependencies": {
|
||||||
|
"busboy": "^1.6.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/express-validator": {
|
||||||
|
"version": "7.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.0.1.tgz",
|
||||||
|
"integrity": "sha512-oB+z9QOzQIE8FnlINqyIFA8eIckahC6qc8KtqLdLJcU3/phVyuhXH3bA4qzcrhme+1RYaCSwrq+TlZ/kAKIARA==",
|
||||||
|
"dependencies": {
|
||||||
|
"lodash": "^4.17.21",
|
||||||
|
"validator": "^13.9.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/express/node_modules/body-parser": {
|
"node_modules/express/node_modules/body-parser": {
|
||||||
"version": "1.20.1",
|
"version": "1.20.1",
|
||||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz",
|
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz",
|
||||||
|
@ -547,9 +756,9 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/follow-redirects": {
|
"node_modules/follow-redirects": {
|
||||||
"version": "1.15.5",
|
"version": "1.15.6",
|
||||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz",
|
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
|
||||||
"integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==",
|
"integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "individual",
|
"type": "individual",
|
||||||
|
@ -565,19 +774,6 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/form-data": {
|
|
||||||
"version": "4.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
|
|
||||||
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
|
|
||||||
"dependencies": {
|
|
||||||
"asynckit": "^0.4.0",
|
|
||||||
"combined-stream": "^1.0.8",
|
|
||||||
"mime-types": "^2.1.12"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/forwarded": {
|
"node_modules/forwarded": {
|
||||||
"version": "0.2.0",
|
"version": "0.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
||||||
|
@ -594,6 +790,33 @@
|
||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/fs-minipass": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
|
||||||
|
"dependencies": {
|
||||||
|
"minipass": "^3.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/fs-minipass/node_modules/minipass": {
|
||||||
|
"version": "3.3.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
|
||||||
|
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
|
||||||
|
"dependencies": {
|
||||||
|
"yallist": "^4.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/fs.realpath": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="
|
||||||
|
},
|
||||||
"node_modules/function-bind": {
|
"node_modules/function-bind": {
|
||||||
"version": "1.1.2",
|
"version": "1.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||||
|
@ -602,6 +825,25 @@
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/gauge": {
|
||||||
|
"version": "3.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz",
|
||||||
|
"integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==",
|
||||||
|
"dependencies": {
|
||||||
|
"aproba": "^1.0.3 || ^2.0.0",
|
||||||
|
"color-support": "^1.1.2",
|
||||||
|
"console-control-strings": "^1.0.0",
|
||||||
|
"has-unicode": "^2.0.1",
|
||||||
|
"object-assign": "^4.1.1",
|
||||||
|
"signal-exit": "^3.0.0",
|
||||||
|
"string-width": "^4.2.3",
|
||||||
|
"strip-ansi": "^6.0.1",
|
||||||
|
"wide-align": "^1.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/get-intrinsic": {
|
"node_modules/get-intrinsic": {
|
||||||
"version": "1.2.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz",
|
||||||
|
@ -620,6 +862,25 @@
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/glob": {
|
||||||
|
"version": "7.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
||||||
|
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
||||||
|
"dependencies": {
|
||||||
|
"fs.realpath": "^1.0.0",
|
||||||
|
"inflight": "^1.0.4",
|
||||||
|
"inherits": "2",
|
||||||
|
"minimatch": "^3.1.1",
|
||||||
|
"once": "^1.3.0",
|
||||||
|
"path-is-absolute": "^1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "*"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/glob-parent": {
|
"node_modules/glob-parent": {
|
||||||
"version": "5.1.2",
|
"version": "5.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
||||||
|
@ -683,6 +944,11 @@
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/has-unicode": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ=="
|
||||||
|
},
|
||||||
"node_modules/hasown": {
|
"node_modules/hasown": {
|
||||||
"version": "2.0.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.1.tgz",
|
||||||
|
@ -709,6 +975,39 @@
|
||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/https-proxy-agent": {
|
||||||
|
"version": "5.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
|
||||||
|
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
|
||||||
|
"dependencies": {
|
||||||
|
"agent-base": "6",
|
||||||
|
"debug": "4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/https-proxy-agent/node_modules/debug": {
|
||||||
|
"version": "4.3.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
|
||||||
|
"integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"ms": "2.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"supports-color": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/https-proxy-agent/node_modules/ms": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
|
||||||
|
},
|
||||||
"node_modules/iconv-lite": {
|
"node_modules/iconv-lite": {
|
||||||
"version": "0.4.24",
|
"version": "0.4.24",
|
||||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||||
|
@ -725,6 +1024,15 @@
|
||||||
"resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz",
|
||||||
"integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA=="
|
"integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA=="
|
||||||
},
|
},
|
||||||
|
"node_modules/inflight": {
|
||||||
|
"version": "1.0.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
||||||
|
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
|
||||||
|
"dependencies": {
|
||||||
|
"once": "^1.3.0",
|
||||||
|
"wrappy": "1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/inherits": {
|
"node_modules/inherits": {
|
||||||
"version": "2.0.4",
|
"version": "2.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||||
|
@ -769,6 +1077,14 @@
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/is-fullwidth-code-point": {
|
||||||
|
"version": "3.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||||
|
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/is-glob": {
|
"node_modules/is-glob": {
|
||||||
"version": "4.0.3",
|
"version": "4.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
|
||||||
|
@ -861,6 +1177,28 @@
|
||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/make-dir": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
|
||||||
|
"dependencies": {
|
||||||
|
"semver": "^6.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/make-dir/node_modules/semver": {
|
||||||
|
"version": "6.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
|
||||||
|
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
|
||||||
|
"bin": {
|
||||||
|
"semver": "bin/semver.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/media-typer": {
|
"node_modules/media-typer": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
|
||||||
|
@ -937,6 +1275,37 @@
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/minipass": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/minizlib": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
|
||||||
|
"dependencies": {
|
||||||
|
"minipass": "^3.0.0",
|
||||||
|
"yallist": "^4.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/minizlib/node_modules/minipass": {
|
||||||
|
"version": "3.3.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
|
||||||
|
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
|
||||||
|
"dependencies": {
|
||||||
|
"yallist": "^4.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/mkdirp": {
|
"node_modules/mkdirp": {
|
||||||
"version": "0.5.6",
|
"version": "0.5.6",
|
||||||
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
|
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
|
||||||
|
@ -1015,6 +1384,32 @@
|
||||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
|
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
|
||||||
},
|
},
|
||||||
|
"node_modules/morgan": {
|
||||||
|
"version": "1.10.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz",
|
||||||
|
"integrity": "sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"basic-auth": "~2.0.1",
|
||||||
|
"debug": "2.6.9",
|
||||||
|
"depd": "~2.0.0",
|
||||||
|
"on-finished": "~2.3.0",
|
||||||
|
"on-headers": "~1.0.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/morgan/node_modules/on-finished": {
|
||||||
|
"version": "2.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
|
||||||
|
"integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==",
|
||||||
|
"dependencies": {
|
||||||
|
"ee-first": "1.1.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/mpath": {
|
"node_modules/mpath": {
|
||||||
"version": "0.9.0",
|
"version": "0.9.0",
|
||||||
"resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz",
|
"resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz",
|
||||||
|
@ -1061,22 +1456,57 @@
|
||||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
|
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
|
||||||
},
|
},
|
||||||
"node_modules/multer": {
|
"node_modules/multer": {
|
||||||
"version": "1.4.5-lts.1",
|
"version": "1.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz",
|
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.3.tgz",
|
||||||
"integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==",
|
"integrity": "sha512-np0YLKncuZoTzufbkM6wEKp68EhWJXcU6fq6QqrSwkckd2LlMgd1UqhUJLj6NS/5sZ8dE8LYDWslsltJznnXlg==",
|
||||||
|
"deprecated": "Multer 1.x is affected by CVE-2022-24434. This is fixed in v1.4.4-lts.1 which drops support for versions of Node.js before 6. Please upgrade to at least Node.js 6 and version 1.4.4-lts.1 of Multer. If you need support for older versions of Node.js, we are open to accepting patches that would fix the CVE on the main 1.x release line, whilst maintaining compatibility with Node.js 0.10.",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"append-field": "^1.0.0",
|
"append-field": "^1.0.0",
|
||||||
"busboy": "^1.0.0",
|
"busboy": "^0.2.11",
|
||||||
"concat-stream": "^1.5.2",
|
"concat-stream": "^1.5.2",
|
||||||
"mkdirp": "^0.5.4",
|
"mkdirp": "^0.5.4",
|
||||||
"object-assign": "^4.1.1",
|
"object-assign": "^4.1.1",
|
||||||
|
"on-finished": "^2.3.0",
|
||||||
"type-is": "^1.6.4",
|
"type-is": "^1.6.4",
|
||||||
"xtend": "^4.0.0"
|
"xtend": "^4.0.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 6.0.0"
|
"node": ">= 0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/multer/node_modules/busboy": {
|
||||||
|
"version": "0.2.14",
|
||||||
|
"resolved": "https://registry.npmjs.org/busboy/-/busboy-0.2.14.tgz",
|
||||||
|
"integrity": "sha512-InWFDomvlkEj+xWLBfU3AvnbVYqeTWmQopiW0tWWEy5yehYm2YkGEc59sUmw/4ty5Zj/b0WHGs1LgecuBSBGrg==",
|
||||||
|
"dependencies": {
|
||||||
|
"dicer": "0.2.5",
|
||||||
|
"readable-stream": "1.1.x"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/multer/node_modules/isarray": {
|
||||||
|
"version": "0.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
|
||||||
|
"integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ=="
|
||||||
|
},
|
||||||
|
"node_modules/multer/node_modules/readable-stream": {
|
||||||
|
"version": "1.1.14",
|
||||||
|
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
|
||||||
|
"integrity": "sha512-+MeVjFf4L44XUkhM1eYbD8fyEsxcV81pqMSR5gblfcLCHfZvbrqy4/qYHE+/R5HoBUT11WV5O08Cr1n3YXkWVQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"core-util-is": "~1.0.0",
|
||||||
|
"inherits": "~2.0.1",
|
||||||
|
"isarray": "0.0.1",
|
||||||
|
"string_decoder": "~0.10.x"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/multer/node_modules/string_decoder": {
|
||||||
|
"version": "0.10.31",
|
||||||
|
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
|
||||||
|
"integrity": "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ=="
|
||||||
|
},
|
||||||
"node_modules/natural": {
|
"node_modules/natural": {
|
||||||
"version": "6.10.0",
|
"version": "6.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/natural/-/natural-6.10.0.tgz",
|
"resolved": "https://registry.npmjs.org/natural/-/natural-6.10.0.tgz",
|
||||||
|
@ -1103,6 +1533,49 @@
|
||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/node-addon-api": {
|
||||||
|
"version": "5.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz",
|
||||||
|
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA=="
|
||||||
|
},
|
||||||
|
"node_modules/node-fetch": {
|
||||||
|
"version": "2.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
|
||||||
|
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
|
||||||
|
"dependencies": {
|
||||||
|
"whatwg-url": "^5.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "4.x || >=6.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"encoding": "^0.1.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"encoding": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/node-fetch/node_modules/tr46": {
|
||||||
|
"version": "0.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
||||||
|
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
|
||||||
|
},
|
||||||
|
"node_modules/node-fetch/node_modules/webidl-conversions": {
|
||||||
|
"version": "3.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
|
||||||
|
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
|
||||||
|
},
|
||||||
|
"node_modules/node-fetch/node_modules/whatwg-url": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
|
||||||
|
"dependencies": {
|
||||||
|
"tr46": "~0.0.3",
|
||||||
|
"webidl-conversions": "^3.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/nodemailer": {
|
"node_modules/nodemailer": {
|
||||||
"version": "6.9.3",
|
"version": "6.9.3",
|
||||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.3.tgz",
|
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.3.tgz",
|
||||||
|
@ -1181,6 +1654,17 @@
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/npmlog": {
|
||||||
|
"version": "5.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz",
|
||||||
|
"integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==",
|
||||||
|
"dependencies": {
|
||||||
|
"are-we-there-yet": "^2.0.0",
|
||||||
|
"console-control-strings": "^1.1.0",
|
||||||
|
"gauge": "^3.0.0",
|
||||||
|
"set-blocking": "^2.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/object-assign": {
|
"node_modules/object-assign": {
|
||||||
"version": "4.1.1",
|
"version": "4.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||||
|
@ -1208,6 +1692,22 @@
|
||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/on-headers": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/once": {
|
||||||
|
"version": "1.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
||||||
|
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
|
||||||
|
"dependencies": {
|
||||||
|
"wrappy": "1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/parseurl": {
|
"node_modules/parseurl": {
|
||||||
"version": "1.3.3",
|
"version": "1.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
||||||
|
@ -1225,6 +1725,14 @@
|
||||||
"util": "^0.10.3"
|
"util": "^0.10.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/path-is-absolute": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/path-to-regexp": {
|
"node_modules/path-to-regexp": {
|
||||||
"version": "0.1.7",
|
"version": "0.1.7",
|
||||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
|
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
|
||||||
|
@ -1266,11 +1774,6 @@
|
||||||
"node": ">= 0.10"
|
"node": ">= 0.10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/proxy-from-env": {
|
|
||||||
"version": "1.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
|
||||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
|
|
||||||
},
|
|
||||||
"node_modules/pstree.remy": {
|
"node_modules/pstree.remy": {
|
||||||
"version": "1.1.8",
|
"version": "1.1.8",
|
||||||
"resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
|
"resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
|
||||||
|
@ -1350,6 +1853,20 @@
|
||||||
"node": ">=8.10.0"
|
"node": ">=8.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/rimraf": {
|
||||||
|
"version": "3.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
|
||||||
|
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
|
||||||
|
"dependencies": {
|
||||||
|
"glob": "^7.1.3"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"rimraf": "bin.js"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/safe-buffer": {
|
"node_modules/safe-buffer": {
|
||||||
"version": "5.2.1",
|
"version": "5.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||||
|
@ -1450,6 +1967,11 @@
|
||||||
"node": ">= 0.8.0"
|
"node": ">= 0.8.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/set-blocking": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="
|
||||||
|
},
|
||||||
"node_modules/set-function-length": {
|
"node_modules/set-function-length": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.1.tgz",
|
||||||
|
@ -1493,6 +2015,11 @@
|
||||||
"resolved": "https://registry.npmjs.org/sift/-/sift-16.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/sift/-/sift-16.0.1.tgz",
|
||||||
"integrity": "sha512-Wv6BjQ5zbhW7VFefWusVP33T/EM0vYikCaQ2qR8yULbsilAT8/wQaXvuQ3ptGLpoKx+lihJE3y2UTgKDyyNHZQ=="
|
"integrity": "sha512-Wv6BjQ5zbhW7VFefWusVP33T/EM0vYikCaQ2qR8yULbsilAT8/wQaXvuQ3ptGLpoKx+lihJE3y2UTgKDyyNHZQ=="
|
||||||
},
|
},
|
||||||
|
"node_modules/signal-exit": {
|
||||||
|
"version": "3.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
|
||||||
|
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="
|
||||||
|
},
|
||||||
"node_modules/simple-update-notifier": {
|
"node_modules/simple-update-notifier": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
|
||||||
|
@ -1577,6 +2104,30 @@
|
||||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||||
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
|
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
|
||||||
},
|
},
|
||||||
|
"node_modules/string-width": {
|
||||||
|
"version": "4.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||||
|
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||||
|
"dependencies": {
|
||||||
|
"emoji-regex": "^8.0.0",
|
||||||
|
"is-fullwidth-code-point": "^3.0.0",
|
||||||
|
"strip-ansi": "^6.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/strip-ansi": {
|
||||||
|
"version": "6.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||||
|
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-regex": "^5.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/supports-color": {
|
"node_modules/supports-color": {
|
||||||
"version": "5.5.0",
|
"version": "5.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
|
||||||
|
@ -1596,6 +2147,33 @@
|
||||||
"node": ">=0.2.6"
|
"node": ">=0.2.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/tar": {
|
||||||
|
"version": "6.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.0.tgz",
|
||||||
|
"integrity": "sha512-/Wo7DcT0u5HUV486xg675HtjNd3BXZ6xDbzsCUZPt5iw8bTQ63bP0Raut3mvro9u+CUyq7YQd8Cx55fsZXxqLQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"chownr": "^2.0.0",
|
||||||
|
"fs-minipass": "^2.0.0",
|
||||||
|
"minipass": "^5.0.0",
|
||||||
|
"minizlib": "^2.1.1",
|
||||||
|
"mkdirp": "^1.0.3",
|
||||||
|
"yallist": "^4.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/tar/node_modules/mkdirp": {
|
||||||
|
"version": "1.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
|
||||||
|
"integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
|
||||||
|
"bin": {
|
||||||
|
"mkdirp": "bin/cmd.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/to-regex-range": {
|
"node_modules/to-regex-range": {
|
||||||
"version": "5.0.1",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||||
|
@ -1703,6 +2281,14 @@
|
||||||
"node": ">= 0.4.0"
|
"node": ">= 0.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/validator": {
|
||||||
|
"version": "13.11.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/validator/-/validator-13.11.0.tgz",
|
||||||
|
"integrity": "sha512-Ii+sehpSfZy+At5nPdnyMhx78fEoPDkR2XW/zimHEL3MyGJQOCQ7WeP20jPYRz7ZCpcKLB21NxuXHF3bxjStBQ==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.10"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/vary": {
|
"node_modules/vary": {
|
||||||
"version": "1.1.2",
|
"version": "1.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
||||||
|
@ -1731,6 +2317,14 @@
|
||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/wide-align": {
|
||||||
|
"version": "1.1.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz",
|
||||||
|
"integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==",
|
||||||
|
"dependencies": {
|
||||||
|
"string-width": "^1.0.2 || 2 || 3 || 4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/wordnet-db": {
|
"node_modules/wordnet-db": {
|
||||||
"version": "3.1.14",
|
"version": "3.1.14",
|
||||||
"resolved": "https://registry.npmjs.org/wordnet-db/-/wordnet-db-3.1.14.tgz",
|
"resolved": "https://registry.npmjs.org/wordnet-db/-/wordnet-db-3.1.14.tgz",
|
||||||
|
@ -1739,6 +2333,11 @@
|
||||||
"node": ">=0.6.0"
|
"node": ">=0.6.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/wrappy": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
|
||||||
|
},
|
||||||
"node_modules/xtend": {
|
"node_modules/xtend": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||||
|
|
|
@ -1,21 +0,0 @@
|
||||||
The MIT License (MIT)
|
|
||||||
|
|
||||||
Copyright (c) 2016 Alex Indigo
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
|
@ -1,233 +0,0 @@
|
||||||
# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit)
|
|
||||||
|
|
||||||
Minimal async jobs utility library, with streams support.
|
|
||||||
|
|
||||||
[![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit)
|
|
||||||
[![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit)
|
|
||||||
[![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit)
|
|
||||||
|
|
||||||
[![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master)
|
|
||||||
[![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit)
|
|
||||||
[![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit)
|
|
||||||
|
|
||||||
<!-- [![Readme](https://img.shields.io/badge/readme-tested-brightgreen.svg?style=flat)](https://www.npmjs.com/package/reamde) -->
|
|
||||||
|
|
||||||
AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects.
|
|
||||||
Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method.
|
|
||||||
|
|
||||||
It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators.
|
|
||||||
|
|
||||||
| compression | size |
|
|
||||||
| :----------------- | -------: |
|
|
||||||
| asynckit.js | 12.34 kB |
|
|
||||||
| asynckit.min.js | 4.11 kB |
|
|
||||||
| asynckit.min.js.gz | 1.47 kB |
|
|
||||||
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
```sh
|
|
||||||
$ npm install --save asynckit
|
|
||||||
```
|
|
||||||
|
|
||||||
## Examples
|
|
||||||
|
|
||||||
### Parallel Jobs
|
|
||||||
|
|
||||||
Runs iterator over provided array in parallel. Stores output in the `result` array,
|
|
||||||
on the matching positions. In unlikely event of an error from one of the jobs,
|
|
||||||
will terminate rest of the active jobs (if abort function is provided)
|
|
||||||
and return error along with salvaged data to the main callback function.
|
|
||||||
|
|
||||||
#### Input Array
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var parallel = require('asynckit').parallel
|
|
||||||
, assert = require('assert')
|
|
||||||
;
|
|
||||||
|
|
||||||
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
|
|
||||||
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
|
|
||||||
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
|
|
||||||
, target = []
|
|
||||||
;
|
|
||||||
|
|
||||||
parallel(source, asyncJob, function(err, result)
|
|
||||||
{
|
|
||||||
assert.deepEqual(result, expectedResult);
|
|
||||||
assert.deepEqual(target, expectedTarget);
|
|
||||||
});
|
|
||||||
|
|
||||||
// async job accepts one element from the array
|
|
||||||
// and a callback function
|
|
||||||
function asyncJob(item, cb)
|
|
||||||
{
|
|
||||||
// different delays (in ms) per item
|
|
||||||
var delay = item * 25;
|
|
||||||
|
|
||||||
// pretend different jobs take different time to finish
|
|
||||||
// and not in consequential order
|
|
||||||
var timeoutId = setTimeout(function() {
|
|
||||||
target.push(item);
|
|
||||||
cb(null, item * 2);
|
|
||||||
}, delay);
|
|
||||||
|
|
||||||
// allow to cancel "leftover" jobs upon error
|
|
||||||
// return function, invoking of which will abort this job
|
|
||||||
return clearTimeout.bind(null, timeoutId);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js).
|
|
||||||
|
|
||||||
#### Input Object
|
|
||||||
|
|
||||||
Also it supports named jobs, listed via object.
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var parallel = require('asynckit/parallel')
|
|
||||||
, assert = require('assert')
|
|
||||||
;
|
|
||||||
|
|
||||||
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
|
|
||||||
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
|
|
||||||
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
|
|
||||||
, expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ]
|
|
||||||
, target = []
|
|
||||||
, keys = []
|
|
||||||
;
|
|
||||||
|
|
||||||
parallel(source, asyncJob, function(err, result)
|
|
||||||
{
|
|
||||||
assert.deepEqual(result, expectedResult);
|
|
||||||
assert.deepEqual(target, expectedTarget);
|
|
||||||
assert.deepEqual(keys, expectedKeys);
|
|
||||||
});
|
|
||||||
|
|
||||||
// supports full value, key, callback (shortcut) interface
|
|
||||||
function asyncJob(item, key, cb)
|
|
||||||
{
|
|
||||||
// different delays (in ms) per item
|
|
||||||
var delay = item * 25;
|
|
||||||
|
|
||||||
// pretend different jobs take different time to finish
|
|
||||||
// and not in consequential order
|
|
||||||
var timeoutId = setTimeout(function() {
|
|
||||||
keys.push(key);
|
|
||||||
target.push(item);
|
|
||||||
cb(null, item * 2);
|
|
||||||
}, delay);
|
|
||||||
|
|
||||||
// allow to cancel "leftover" jobs upon error
|
|
||||||
// return function, invoking of which will abort this job
|
|
||||||
return clearTimeout.bind(null, timeoutId);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js).
|
|
||||||
|
|
||||||
### Serial Jobs
|
|
||||||
|
|
||||||
Runs iterator over provided array sequentially. Stores output in the `result` array,
|
|
||||||
on the matching positions. In unlikely event of an error from one of the jobs,
|
|
||||||
will not proceed to the rest of the items in the list
|
|
||||||
and return error along with salvaged data to the main callback function.
|
|
||||||
|
|
||||||
#### Input Array
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var serial = require('asynckit/serial')
|
|
||||||
, assert = require('assert')
|
|
||||||
;
|
|
||||||
|
|
||||||
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
|
|
||||||
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
|
|
||||||
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
|
|
||||||
, target = []
|
|
||||||
;
|
|
||||||
|
|
||||||
serial(source, asyncJob, function(err, result)
|
|
||||||
{
|
|
||||||
assert.deepEqual(result, expectedResult);
|
|
||||||
assert.deepEqual(target, expectedTarget);
|
|
||||||
});
|
|
||||||
|
|
||||||
// extended interface (item, key, callback)
|
|
||||||
// also supported for arrays
|
|
||||||
function asyncJob(item, key, cb)
|
|
||||||
{
|
|
||||||
target.push(key);
|
|
||||||
|
|
||||||
// it will be automatically made async
|
|
||||||
// even it iterator "returns" in the same event loop
|
|
||||||
cb(null, item * 2);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
More examples could be found in [test/test-serial-array.js](test/test-serial-array.js).
|
|
||||||
|
|
||||||
#### Input Object
|
|
||||||
|
|
||||||
Also it supports named jobs, listed via object.
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var serial = require('asynckit').serial
|
|
||||||
, assert = require('assert')
|
|
||||||
;
|
|
||||||
|
|
||||||
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
|
|
||||||
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
|
|
||||||
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
|
|
||||||
, target = []
|
|
||||||
;
|
|
||||||
|
|
||||||
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
|
|
||||||
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
|
|
||||||
, expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
|
|
||||||
, target = []
|
|
||||||
;
|
|
||||||
|
|
||||||
|
|
||||||
serial(source, asyncJob, function(err, result)
|
|
||||||
{
|
|
||||||
assert.deepEqual(result, expectedResult);
|
|
||||||
assert.deepEqual(target, expectedTarget);
|
|
||||||
});
|
|
||||||
|
|
||||||
// shortcut interface (item, callback)
|
|
||||||
// works for object as well as for the arrays
|
|
||||||
function asyncJob(item, cb)
|
|
||||||
{
|
|
||||||
target.push(item);
|
|
||||||
|
|
||||||
// it will be automatically made async
|
|
||||||
// even it iterator "returns" in the same event loop
|
|
||||||
cb(null, item * 2);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
More examples could be found in [test/test-serial-object.js](test/test-serial-object.js).
|
|
||||||
|
|
||||||
_Note: Since _object_ is an _unordered_ collection of properties,
|
|
||||||
it may produce unexpected results with sequential iterations.
|
|
||||||
Whenever order of the jobs' execution is important please use `serialOrdered` method._
|
|
||||||
|
|
||||||
### Ordered Serial Iterations
|
|
||||||
|
|
||||||
TBD
|
|
||||||
|
|
||||||
For example [compare-property](compare-property) package.
|
|
||||||
|
|
||||||
### Streaming interface
|
|
||||||
|
|
||||||
TBD
|
|
||||||
|
|
||||||
## Want to Know More?
|
|
||||||
|
|
||||||
More examples can be found in [test folder](test/).
|
|
||||||
|
|
||||||
Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions.
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
AsyncKit is licensed under the MIT license.
|
|
|
@ -1,76 +0,0 @@
|
||||||
/* eslint no-console: "off" */
|
|
||||||
|
|
||||||
var asynckit = require('./')
|
|
||||||
, async = require('async')
|
|
||||||
, assert = require('assert')
|
|
||||||
, expected = 0
|
|
||||||
;
|
|
||||||
|
|
||||||
var Benchmark = require('benchmark');
|
|
||||||
var suite = new Benchmark.Suite;
|
|
||||||
|
|
||||||
var source = [];
|
|
||||||
for (var z = 1; z < 100; z++)
|
|
||||||
{
|
|
||||||
source.push(z);
|
|
||||||
expected += z;
|
|
||||||
}
|
|
||||||
|
|
||||||
suite
|
|
||||||
// add tests
|
|
||||||
|
|
||||||
.add('async.map', function(deferred)
|
|
||||||
{
|
|
||||||
var total = 0;
|
|
||||||
|
|
||||||
async.map(source,
|
|
||||||
function(i, cb)
|
|
||||||
{
|
|
||||||
setImmediate(function()
|
|
||||||
{
|
|
||||||
total += i;
|
|
||||||
cb(null, total);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function(err, result)
|
|
||||||
{
|
|
||||||
assert.ifError(err);
|
|
||||||
assert.equal(result[result.length - 1], expected);
|
|
||||||
deferred.resolve();
|
|
||||||
});
|
|
||||||
}, {'defer': true})
|
|
||||||
|
|
||||||
|
|
||||||
.add('asynckit.parallel', function(deferred)
|
|
||||||
{
|
|
||||||
var total = 0;
|
|
||||||
|
|
||||||
asynckit.parallel(source,
|
|
||||||
function(i, cb)
|
|
||||||
{
|
|
||||||
setImmediate(function()
|
|
||||||
{
|
|
||||||
total += i;
|
|
||||||
cb(null, total);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
function(err, result)
|
|
||||||
{
|
|
||||||
assert.ifError(err);
|
|
||||||
assert.equal(result[result.length - 1], expected);
|
|
||||||
deferred.resolve();
|
|
||||||
});
|
|
||||||
}, {'defer': true})
|
|
||||||
|
|
||||||
|
|
||||||
// add listeners
|
|
||||||
.on('cycle', function(ev)
|
|
||||||
{
|
|
||||||
console.log(String(ev.target));
|
|
||||||
})
|
|
||||||
.on('complete', function()
|
|
||||||
{
|
|
||||||
console.log('Fastest is ' + this.filter('fastest').map('name'));
|
|
||||||
})
|
|
||||||
// run async
|
|
||||||
.run({ 'async': true });
|
|
|
@ -1,6 +0,0 @@
|
||||||
module.exports =
|
|
||||||
{
|
|
||||||
parallel : require('./parallel.js'),
|
|
||||||
serial : require('./serial.js'),
|
|
||||||
serialOrdered : require('./serialOrdered.js')
|
|
||||||
};
|
|
|
@ -1,29 +0,0 @@
|
||||||
// API
|
|
||||||
module.exports = abort;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Aborts leftover active jobs
|
|
||||||
*
|
|
||||||
* @param {object} state - current state object
|
|
||||||
*/
|
|
||||||
function abort(state)
|
|
||||||
{
|
|
||||||
Object.keys(state.jobs).forEach(clean.bind(state));
|
|
||||||
|
|
||||||
// reset leftover jobs
|
|
||||||
state.jobs = {};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cleans up leftover job by invoking abort function for the provided job id
|
|
||||||
*
|
|
||||||
* @this state
|
|
||||||
* @param {string|number} key - job id to abort
|
|
||||||
*/
|
|
||||||
function clean(key)
|
|
||||||
{
|
|
||||||
if (typeof this.jobs[key] == 'function')
|
|
||||||
{
|
|
||||||
this.jobs[key]();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,34 +0,0 @@
|
||||||
var defer = require('./defer.js');
|
|
||||||
|
|
||||||
// API
|
|
||||||
module.exports = async;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs provided callback asynchronously
|
|
||||||
* even if callback itself is not
|
|
||||||
*
|
|
||||||
* @param {function} callback - callback to invoke
|
|
||||||
* @returns {function} - augmented callback
|
|
||||||
*/
|
|
||||||
function async(callback)
|
|
||||||
{
|
|
||||||
var isAsync = false;
|
|
||||||
|
|
||||||
// check if async happened
|
|
||||||
defer(function() { isAsync = true; });
|
|
||||||
|
|
||||||
return function async_callback(err, result)
|
|
||||||
{
|
|
||||||
if (isAsync)
|
|
||||||
{
|
|
||||||
callback(err, result);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
defer(function nextTick_callback()
|
|
||||||
{
|
|
||||||
callback(err, result);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
|
@ -1,26 +0,0 @@
|
||||||
module.exports = defer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs provided function on next iteration of the event loop
|
|
||||||
*
|
|
||||||
* @param {function} fn - function to run
|
|
||||||
*/
|
|
||||||
function defer(fn)
|
|
||||||
{
|
|
||||||
var nextTick = typeof setImmediate == 'function'
|
|
||||||
? setImmediate
|
|
||||||
: (
|
|
||||||
typeof process == 'object' && typeof process.nextTick == 'function'
|
|
||||||
? process.nextTick
|
|
||||||
: null
|
|
||||||
);
|
|
||||||
|
|
||||||
if (nextTick)
|
|
||||||
{
|
|
||||||
nextTick(fn);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
setTimeout(fn, 0);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,75 +0,0 @@
|
||||||
var async = require('./async.js')
|
|
||||||
, abort = require('./abort.js')
|
|
||||||
;
|
|
||||||
|
|
||||||
// API
|
|
||||||
module.exports = iterate;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Iterates over each job object
|
|
||||||
*
|
|
||||||
* @param {array|object} list - array or object (named list) to iterate over
|
|
||||||
* @param {function} iterator - iterator to run
|
|
||||||
* @param {object} state - current job status
|
|
||||||
* @param {function} callback - invoked when all elements processed
|
|
||||||
*/
|
|
||||||
function iterate(list, iterator, state, callback)
|
|
||||||
{
|
|
||||||
// store current index
|
|
||||||
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
|
|
||||||
|
|
||||||
state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
|
|
||||||
{
|
|
||||||
// don't repeat yourself
|
|
||||||
// skip secondary callbacks
|
|
||||||
if (!(key in state.jobs))
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// clean up jobs
|
|
||||||
delete state.jobs[key];
|
|
||||||
|
|
||||||
if (error)
|
|
||||||
{
|
|
||||||
// don't process rest of the results
|
|
||||||
// stop still active jobs
|
|
||||||
// and reset the list
|
|
||||||
abort(state);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
state.results[key] = output;
|
|
||||||
}
|
|
||||||
|
|
||||||
// return salvaged results
|
|
||||||
callback(error, state.results);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs iterator over provided job element
|
|
||||||
*
|
|
||||||
* @param {function} iterator - iterator to invoke
|
|
||||||
* @param {string|number} key - key/index of the element in the list of jobs
|
|
||||||
* @param {mixed} item - job description
|
|
||||||
* @param {function} callback - invoked after iterator is done with the job
|
|
||||||
* @returns {function|mixed} - job abort function or something else
|
|
||||||
*/
|
|
||||||
function runJob(iterator, key, item, callback)
|
|
||||||
{
|
|
||||||
var aborter;
|
|
||||||
|
|
||||||
// allow shortcut if iterator expects only two arguments
|
|
||||||
if (iterator.length == 2)
|
|
||||||
{
|
|
||||||
aborter = iterator(item, async(callback));
|
|
||||||
}
|
|
||||||
// otherwise go with full three arguments
|
|
||||||
else
|
|
||||||
{
|
|
||||||
aborter = iterator(item, key, async(callback));
|
|
||||||
}
|
|
||||||
|
|
||||||
return aborter;
|
|
||||||
}
|
|
|
@ -1,91 +0,0 @@
|
||||||
var streamify = require('./streamify.js')
|
|
||||||
, defer = require('./defer.js')
|
|
||||||
;
|
|
||||||
|
|
||||||
// API
|
|
||||||
module.exports = ReadableAsyncKit;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Base constructor for all streams
|
|
||||||
* used to hold properties/methods
|
|
||||||
*/
|
|
||||||
function ReadableAsyncKit()
|
|
||||||
{
|
|
||||||
ReadableAsyncKit.super_.apply(this, arguments);
|
|
||||||
|
|
||||||
// list of active jobs
|
|
||||||
this.jobs = {};
|
|
||||||
|
|
||||||
// add stream methods
|
|
||||||
this.destroy = destroy;
|
|
||||||
this._start = _start;
|
|
||||||
this._read = _read;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Destroys readable stream,
|
|
||||||
* by aborting outstanding jobs
|
|
||||||
*
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
function destroy()
|
|
||||||
{
|
|
||||||
if (this.destroyed)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.destroyed = true;
|
|
||||||
|
|
||||||
if (typeof this.terminator == 'function')
|
|
||||||
{
|
|
||||||
this.terminator();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Starts provided jobs in async manner
|
|
||||||
*
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
function _start()
|
|
||||||
{
|
|
||||||
// first argument – runner function
|
|
||||||
var runner = arguments[0]
|
|
||||||
// take away first argument
|
|
||||||
, args = Array.prototype.slice.call(arguments, 1)
|
|
||||||
// second argument - input data
|
|
||||||
, input = args[0]
|
|
||||||
// last argument - result callback
|
|
||||||
, endCb = streamify.callback.call(this, args[args.length - 1])
|
|
||||||
;
|
|
||||||
|
|
||||||
args[args.length - 1] = endCb;
|
|
||||||
// third argument - iterator
|
|
||||||
args[1] = streamify.iterator.call(this, args[1]);
|
|
||||||
|
|
||||||
// allow time for proper setup
|
|
||||||
defer(function()
|
|
||||||
{
|
|
||||||
if (!this.destroyed)
|
|
||||||
{
|
|
||||||
this.terminator = runner.apply(null, args);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
endCb(null, Array.isArray(input) ? [] : {});
|
|
||||||
}
|
|
||||||
}.bind(this));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Implement _read to comply with Readable streams
|
|
||||||
* Doesn't really make sense for flowing object mode
|
|
||||||
*
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
function _read()
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
var parallel = require('../parallel.js');
|
|
||||||
|
|
||||||
// API
|
|
||||||
module.exports = ReadableParallel;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Streaming wrapper to `asynckit.parallel`
|
|
||||||
*
|
|
||||||
* @param {array|object} list - array or object (named list) to iterate over
|
|
||||||
* @param {function} iterator - iterator to run
|
|
||||||
* @param {function} callback - invoked when all elements processed
|
|
||||||
* @returns {stream.Readable#}
|
|
||||||
*/
|
|
||||||
function ReadableParallel(list, iterator, callback)
|
|
||||||
{
|
|
||||||
if (!(this instanceof ReadableParallel))
|
|
||||||
{
|
|
||||||
return new ReadableParallel(list, iterator, callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
// turn on object mode
|
|
||||||
ReadableParallel.super_.call(this, {objectMode: true});
|
|
||||||
|
|
||||||
this._start(parallel, list, iterator, callback);
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
var serial = require('../serial.js');
|
|
||||||
|
|
||||||
// API
|
|
||||||
module.exports = ReadableSerial;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Streaming wrapper to `asynckit.serial`
|
|
||||||
*
|
|
||||||
* @param {array|object} list - array or object (named list) to iterate over
|
|
||||||
* @param {function} iterator - iterator to run
|
|
||||||
* @param {function} callback - invoked when all elements processed
|
|
||||||
* @returns {stream.Readable#}
|
|
||||||
*/
|
|
||||||
function ReadableSerial(list, iterator, callback)
|
|
||||||
{
|
|
||||||
if (!(this instanceof ReadableSerial))
|
|
||||||
{
|
|
||||||
return new ReadableSerial(list, iterator, callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
// turn on object mode
|
|
||||||
ReadableSerial.super_.call(this, {objectMode: true});
|
|
||||||
|
|
||||||
this._start(serial, list, iterator, callback);
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
var serialOrdered = require('../serialOrdered.js');
|
|
||||||
|
|
||||||
// API
|
|
||||||
module.exports = ReadableSerialOrdered;
|
|
||||||
// expose sort helpers
|
|
||||||
module.exports.ascending = serialOrdered.ascending;
|
|
||||||
module.exports.descending = serialOrdered.descending;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Streaming wrapper to `asynckit.serialOrdered`
|
|
||||||
*
|
|
||||||
* @param {array|object} list - array or object (named list) to iterate over
|
|
||||||
* @param {function} iterator - iterator to run
|
|
||||||
* @param {function} sortMethod - custom sort function
|
|
||||||
* @param {function} callback - invoked when all elements processed
|
|
||||||
* @returns {stream.Readable#}
|
|
||||||
*/
|
|
||||||
function ReadableSerialOrdered(list, iterator, sortMethod, callback)
|
|
||||||
{
|
|
||||||
if (!(this instanceof ReadableSerialOrdered))
|
|
||||||
{
|
|
||||||
return new ReadableSerialOrdered(list, iterator, sortMethod, callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
// turn on object mode
|
|
||||||
ReadableSerialOrdered.super_.call(this, {objectMode: true});
|
|
||||||
|
|
||||||
this._start(serialOrdered, list, iterator, sortMethod, callback);
|
|
||||||
}
|
|
|
@ -1,37 +0,0 @@
|
||||||
// API
|
|
||||||
module.exports = state;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates initial state object
|
|
||||||
* for iteration over list
|
|
||||||
*
|
|
||||||
* @param {array|object} list - list to iterate over
|
|
||||||
* @param {function|null} sortMethod - function to use for keys sort,
|
|
||||||
* or `null` to keep them as is
|
|
||||||
* @returns {object} - initial state object
|
|
||||||
*/
|
|
||||||
function state(list, sortMethod)
|
|
||||||
{
|
|
||||||
var isNamedList = !Array.isArray(list)
|
|
||||||
, initState =
|
|
||||||
{
|
|
||||||
index : 0,
|
|
||||||
keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
|
|
||||||
jobs : {},
|
|
||||||
results : isNamedList ? {} : [],
|
|
||||||
size : isNamedList ? Object.keys(list).length : list.length
|
|
||||||
}
|
|
||||||
;
|
|
||||||
|
|
||||||
if (sortMethod)
|
|
||||||
{
|
|
||||||
// sort array keys based on it's values
|
|
||||||
// sort object's keys just on own merit
|
|
||||||
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
|
|
||||||
{
|
|
||||||
return sortMethod(list[a], list[b]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return initState;
|
|
||||||
}
|
|
|
@ -1,141 +0,0 @@
|
||||||
var async = require('./async.js');
|
|
||||||
|
|
||||||
// API
|
|
||||||
module.exports = {
|
|
||||||
iterator: wrapIterator,
|
|
||||||
callback: wrapCallback
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wraps iterators with long signature
|
|
||||||
*
|
|
||||||
* @this ReadableAsyncKit#
|
|
||||||
* @param {function} iterator - function to wrap
|
|
||||||
* @returns {function} - wrapped function
|
|
||||||
*/
|
|
||||||
function wrapIterator(iterator)
|
|
||||||
{
|
|
||||||
var stream = this;
|
|
||||||
|
|
||||||
return function(item, key, cb)
|
|
||||||
{
|
|
||||||
var aborter
|
|
||||||
, wrappedCb = async(wrapIteratorCallback.call(stream, cb, key))
|
|
||||||
;
|
|
||||||
|
|
||||||
stream.jobs[key] = wrappedCb;
|
|
||||||
|
|
||||||
// it's either shortcut (item, cb)
|
|
||||||
if (iterator.length == 2)
|
|
||||||
{
|
|
||||||
aborter = iterator(item, wrappedCb);
|
|
||||||
}
|
|
||||||
// or long format (item, key, cb)
|
|
||||||
else
|
|
||||||
{
|
|
||||||
aborter = iterator(item, key, wrappedCb);
|
|
||||||
}
|
|
||||||
|
|
||||||
return aborter;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wraps provided callback function
|
|
||||||
* allowing to execute snitch function before
|
|
||||||
* real callback
|
|
||||||
*
|
|
||||||
* @this ReadableAsyncKit#
|
|
||||||
* @param {function} callback - function to wrap
|
|
||||||
* @returns {function} - wrapped function
|
|
||||||
*/
|
|
||||||
function wrapCallback(callback)
|
|
||||||
{
|
|
||||||
var stream = this;
|
|
||||||
|
|
||||||
var wrapped = function(error, result)
|
|
||||||
{
|
|
||||||
return finisher.call(stream, error, result, callback);
|
|
||||||
};
|
|
||||||
|
|
||||||
return wrapped;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wraps provided iterator callback function
|
|
||||||
* makes sure snitch only called once,
|
|
||||||
* but passes secondary calls to the original callback
|
|
||||||
*
|
|
||||||
* @this ReadableAsyncKit#
|
|
||||||
* @param {function} callback - callback to wrap
|
|
||||||
* @param {number|string} key - iteration key
|
|
||||||
* @returns {function} wrapped callback
|
|
||||||
*/
|
|
||||||
function wrapIteratorCallback(callback, key)
|
|
||||||
{
|
|
||||||
var stream = this;
|
|
||||||
|
|
||||||
return function(error, output)
|
|
||||||
{
|
|
||||||
// don't repeat yourself
|
|
||||||
if (!(key in stream.jobs))
|
|
||||||
{
|
|
||||||
callback(error, output);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// clean up jobs
|
|
||||||
delete stream.jobs[key];
|
|
||||||
|
|
||||||
return streamer.call(stream, error, {key: key, value: output}, callback);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stream wrapper for iterator callback
|
|
||||||
*
|
|
||||||
* @this ReadableAsyncKit#
|
|
||||||
* @param {mixed} error - error response
|
|
||||||
* @param {mixed} output - iterator output
|
|
||||||
* @param {function} callback - callback that expects iterator results
|
|
||||||
*/
|
|
||||||
function streamer(error, output, callback)
|
|
||||||
{
|
|
||||||
if (error && !this.error)
|
|
||||||
{
|
|
||||||
this.error = error;
|
|
||||||
this.pause();
|
|
||||||
this.emit('error', error);
|
|
||||||
// send back value only, as expected
|
|
||||||
callback(error, output && output.value);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// stream stuff
|
|
||||||
this.push(output);
|
|
||||||
|
|
||||||
// back to original track
|
|
||||||
// send back value only, as expected
|
|
||||||
callback(error, output && output.value);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stream wrapper for finishing callback
|
|
||||||
*
|
|
||||||
* @this ReadableAsyncKit#
|
|
||||||
* @param {mixed} error - error response
|
|
||||||
* @param {mixed} output - iterator output
|
|
||||||
* @param {function} callback - callback that expects final results
|
|
||||||
*/
|
|
||||||
function finisher(error, output, callback)
|
|
||||||
{
|
|
||||||
// signal end of the stream
|
|
||||||
// only for successfully finished streams
|
|
||||||
if (!error)
|
|
||||||
{
|
|
||||||
this.push(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
// back to original track
|
|
||||||
callback(error, output);
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
var abort = require('./abort.js')
|
|
||||||
, async = require('./async.js')
|
|
||||||
;
|
|
||||||
|
|
||||||
// API
|
|
||||||
module.exports = terminator;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Terminates jobs in the attached state context
|
|
||||||
*
|
|
||||||
* @this AsyncKitState#
|
|
||||||
* @param {function} callback - final callback to invoke after termination
|
|
||||||
*/
|
|
||||||
function terminator(callback)
|
|
||||||
{
|
|
||||||
if (!Object.keys(this.jobs).length)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// fast forward iteration index
|
|
||||||
this.index = this.size;
|
|
||||||
|
|
||||||
// abort jobs
|
|
||||||
abort(this);
|
|
||||||
|
|
||||||
// send back results we have so far
|
|
||||||
async(callback)(null, this.results);
|
|
||||||
}
|
|
|
@ -1,63 +0,0 @@
|
||||||
{
|
|
||||||
"name": "asynckit",
|
|
||||||
"version": "0.4.0",
|
|
||||||
"description": "Minimal async jobs utility library, with streams support",
|
|
||||||
"main": "index.js",
|
|
||||||
"scripts": {
|
|
||||||
"clean": "rimraf coverage",
|
|
||||||
"lint": "eslint *.js lib/*.js test/*.js",
|
|
||||||
"test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec",
|
|
||||||
"win-test": "tape test/test-*.js",
|
|
||||||
"browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec",
|
|
||||||
"report": "istanbul report",
|
|
||||||
"size": "browserify index.js | size-table asynckit",
|
|
||||||
"debug": "tape test/test-*.js"
|
|
||||||
},
|
|
||||||
"pre-commit": [
|
|
||||||
"clean",
|
|
||||||
"lint",
|
|
||||||
"test",
|
|
||||||
"browser",
|
|
||||||
"report",
|
|
||||||
"size"
|
|
||||||
],
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/alexindigo/asynckit.git"
|
|
||||||
},
|
|
||||||
"keywords": [
|
|
||||||
"async",
|
|
||||||
"jobs",
|
|
||||||
"parallel",
|
|
||||||
"serial",
|
|
||||||
"iterator",
|
|
||||||
"array",
|
|
||||||
"object",
|
|
||||||
"stream",
|
|
||||||
"destroy",
|
|
||||||
"terminate",
|
|
||||||
"abort"
|
|
||||||
],
|
|
||||||
"author": "Alex Indigo <iam@alexindigo.com>",
|
|
||||||
"license": "MIT",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/alexindigo/asynckit/issues"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/alexindigo/asynckit#readme",
|
|
||||||
"devDependencies": {
|
|
||||||
"browserify": "^13.0.0",
|
|
||||||
"browserify-istanbul": "^2.0.0",
|
|
||||||
"coveralls": "^2.11.9",
|
|
||||||
"eslint": "^2.9.0",
|
|
||||||
"istanbul": "^0.4.3",
|
|
||||||
"obake": "^0.1.2",
|
|
||||||
"phantomjs-prebuilt": "^2.1.7",
|
|
||||||
"pre-commit": "^1.1.3",
|
|
||||||
"reamde": "^1.1.0",
|
|
||||||
"rimraf": "^2.5.2",
|
|
||||||
"size-table": "^0.2.0",
|
|
||||||
"tap-spec": "^4.1.1",
|
|
||||||
"tape": "^4.5.1"
|
|
||||||
},
|
|
||||||
"dependencies": {}
|
|
||||||
}
|
|
|
@ -1,43 +0,0 @@
|
||||||
var iterate = require('./lib/iterate.js')
|
|
||||||
, initState = require('./lib/state.js')
|
|
||||||
, terminator = require('./lib/terminator.js')
|
|
||||||
;
|
|
||||||
|
|
||||||
// Public API
|
|
||||||
module.exports = parallel;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs iterator over provided array elements in parallel
|
|
||||||
*
|
|
||||||
* @param {array|object} list - array or object (named list) to iterate over
|
|
||||||
* @param {function} iterator - iterator to run
|
|
||||||
* @param {function} callback - invoked when all elements processed
|
|
||||||
* @returns {function} - jobs terminator
|
|
||||||
*/
|
|
||||||
function parallel(list, iterator, callback)
|
|
||||||
{
|
|
||||||
var state = initState(list);
|
|
||||||
|
|
||||||
while (state.index < (state['keyedList'] || list).length)
|
|
||||||
{
|
|
||||||
iterate(list, iterator, state, function(error, result)
|
|
||||||
{
|
|
||||||
if (error)
|
|
||||||
{
|
|
||||||
callback(error, result);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// looks like it's the last one
|
|
||||||
if (Object.keys(state.jobs).length === 0)
|
|
||||||
{
|
|
||||||
callback(null, state.results);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
state.index++;
|
|
||||||
}
|
|
||||||
|
|
||||||
return terminator.bind(state, callback);
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
var serialOrdered = require('./serialOrdered.js');
|
|
||||||
|
|
||||||
// Public API
|
|
||||||
module.exports = serial;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs iterator over provided array elements in series
|
|
||||||
*
|
|
||||||
* @param {array|object} list - array or object (named list) to iterate over
|
|
||||||
* @param {function} iterator - iterator to run
|
|
||||||
* @param {function} callback - invoked when all elements processed
|
|
||||||
* @returns {function} - jobs terminator
|
|
||||||
*/
|
|
||||||
function serial(list, iterator, callback)
|
|
||||||
{
|
|
||||||
return serialOrdered(list, iterator, null, callback);
|
|
||||||
}
|
|
|
@ -1,75 +0,0 @@
|
||||||
var iterate = require('./lib/iterate.js')
|
|
||||||
, initState = require('./lib/state.js')
|
|
||||||
, terminator = require('./lib/terminator.js')
|
|
||||||
;
|
|
||||||
|
|
||||||
// Public API
|
|
||||||
module.exports = serialOrdered;
|
|
||||||
// sorting helpers
|
|
||||||
module.exports.ascending = ascending;
|
|
||||||
module.exports.descending = descending;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs iterator over provided sorted array elements in series
|
|
||||||
*
|
|
||||||
* @param {array|object} list - array or object (named list) to iterate over
|
|
||||||
* @param {function} iterator - iterator to run
|
|
||||||
* @param {function} sortMethod - custom sort function
|
|
||||||
* @param {function} callback - invoked when all elements processed
|
|
||||||
* @returns {function} - jobs terminator
|
|
||||||
*/
|
|
||||||
function serialOrdered(list, iterator, sortMethod, callback)
|
|
||||||
{
|
|
||||||
var state = initState(list, sortMethod);
|
|
||||||
|
|
||||||
iterate(list, iterator, state, function iteratorHandler(error, result)
|
|
||||||
{
|
|
||||||
if (error)
|
|
||||||
{
|
|
||||||
callback(error, result);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
state.index++;
|
|
||||||
|
|
||||||
// are we there yet?
|
|
||||||
if (state.index < (state['keyedList'] || list).length)
|
|
||||||
{
|
|
||||||
iterate(list, iterator, state, iteratorHandler);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// done here
|
|
||||||
callback(null, state.results);
|
|
||||||
});
|
|
||||||
|
|
||||||
return terminator.bind(state, callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* -- Sort methods
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* sort helper to sort array elements in ascending order
|
|
||||||
*
|
|
||||||
* @param {mixed} a - an item to compare
|
|
||||||
* @param {mixed} b - an item to compare
|
|
||||||
* @returns {number} - comparison result
|
|
||||||
*/
|
|
||||||
function ascending(a, b)
|
|
||||||
{
|
|
||||||
return a < b ? -1 : a > b ? 1 : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* sort helper to sort array elements in descending order
|
|
||||||
*
|
|
||||||
* @param {mixed} a - an item to compare
|
|
||||||
* @param {mixed} b - an item to compare
|
|
||||||
* @returns {number} - comparison result
|
|
||||||
*/
|
|
||||||
function descending(a, b)
|
|
||||||
{
|
|
||||||
return -1 * ascending(a, b);
|
|
||||||
}
|
|
|
@ -1,21 +0,0 @@
|
||||||
var inherits = require('util').inherits
|
|
||||||
, Readable = require('stream').Readable
|
|
||||||
, ReadableAsyncKit = require('./lib/readable_asynckit.js')
|
|
||||||
, ReadableParallel = require('./lib/readable_parallel.js')
|
|
||||||
, ReadableSerial = require('./lib/readable_serial.js')
|
|
||||||
, ReadableSerialOrdered = require('./lib/readable_serial_ordered.js')
|
|
||||||
;
|
|
||||||
|
|
||||||
// API
|
|
||||||
module.exports =
|
|
||||||
{
|
|
||||||
parallel : ReadableParallel,
|
|
||||||
serial : ReadableSerial,
|
|
||||||
serialOrdered : ReadableSerialOrdered,
|
|
||||||
};
|
|
||||||
|
|
||||||
inherits(ReadableAsyncKit, Readable);
|
|
||||||
|
|
||||||
inherits(ReadableParallel, ReadableAsyncKit);
|
|
||||||
inherits(ReadableSerial, ReadableAsyncKit);
|
|
||||||
inherits(ReadableSerialOrdered, ReadableAsyncKit);
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,7 +1,19 @@
|
||||||
# Copyright (c) 2014-present Matt Zabriskie & Collaborators
|
Copyright (c) 2014-present Matt Zabriskie
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
|
|
@ -1,3 +0,0 @@
|
||||||
# Migration Guide
|
|
||||||
|
|
||||||
## 0.x.x -> 1.1.0
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,6 +1,5 @@
|
||||||
# Reporting a Vulnerability
|
# Security Policy
|
||||||
|
|
||||||
If you discover a security vulnerability in axios please disclose it via [our huntr page](https://huntr.dev/repos/axios/axios/). Bounty eligibility, CVE assignment, response times and past reports are all there.
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
Please report security issues to jasonsaayman@gmail.com
|
||||||
Thank you for improving the security of axios.
|
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
@ -1,542 +0,0 @@
|
||||||
interface RawAxiosHeaders {
|
|
||||||
[key: string]: axios.AxiosHeaderValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
type MethodsHeaders = Partial<{
|
|
||||||
[Key in axios.Method as Lowercase<Key>]: AxiosHeaders;
|
|
||||||
} & {common: AxiosHeaders}>;
|
|
||||||
|
|
||||||
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
|
|
||||||
|
|
||||||
type AxiosHeaderParser = (this: AxiosHeaders, value: axios.AxiosHeaderValue, header: string) => any;
|
|
||||||
|
|
||||||
type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent'| 'Content-Encoding' | 'Authorization';
|
|
||||||
|
|
||||||
type ContentType = axios.AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';
|
|
||||||
|
|
||||||
type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control'| 'Content-Encoding';
|
|
||||||
|
|
||||||
declare class AxiosHeaders {
|
|
||||||
constructor(
|
|
||||||
headers?: RawAxiosHeaders | AxiosHeaders | string
|
|
||||||
);
|
|
||||||
|
|
||||||
[key: string]: any;
|
|
||||||
|
|
||||||
set(headerName?: string, value?: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
|
|
||||||
|
|
||||||
get(headerName: string, parser: RegExp): RegExpExecArray | null;
|
|
||||||
get(headerName: string, matcher?: true | AxiosHeaderParser): axios.AxiosHeaderValue;
|
|
||||||
|
|
||||||
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
clear(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
normalize(format: boolean): AxiosHeaders;
|
|
||||||
|
|
||||||
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
|
|
||||||
|
|
||||||
toJSON(asStrings?: boolean): RawAxiosHeaders;
|
|
||||||
|
|
||||||
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
|
|
||||||
|
|
||||||
static accessor(header: string | string[]): AxiosHeaders;
|
|
||||||
|
|
||||||
static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
|
|
||||||
|
|
||||||
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getContentType(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getContentType(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
|
|
||||||
hasContentType(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setContentLength(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getContentLength(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getContentLength(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
|
|
||||||
hasContentLength(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setAccept(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getAccept(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getAccept(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
|
|
||||||
hasAccept(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setUserAgent(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getUserAgent(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getUserAgent(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
|
|
||||||
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setContentEncoding(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getContentEncoding(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getContentEncoding(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
|
|
||||||
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setAuthorization(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getAuthorization(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getAuthorization(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
|
|
||||||
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
[Symbol.iterator](): IterableIterator<[string, axios.AxiosHeaderValue]>;
|
|
||||||
}
|
|
||||||
|
|
||||||
declare class AxiosError<T = unknown, D = any> extends Error {
|
|
||||||
constructor(
|
|
||||||
message?: string,
|
|
||||||
code?: string,
|
|
||||||
config?: axios.InternalAxiosRequestConfig<D>,
|
|
||||||
request?: any,
|
|
||||||
response?: axios.AxiosResponse<T, D>
|
|
||||||
);
|
|
||||||
|
|
||||||
config?: axios.InternalAxiosRequestConfig<D>;
|
|
||||||
code?: string;
|
|
||||||
request?: any;
|
|
||||||
response?: axios.AxiosResponse<T, D>;
|
|
||||||
isAxiosError: boolean;
|
|
||||||
status?: number;
|
|
||||||
toJSON: () => object;
|
|
||||||
cause?: Error;
|
|
||||||
static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
|
|
||||||
static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
|
|
||||||
static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";
|
|
||||||
static readonly ERR_NETWORK = "ERR_NETWORK";
|
|
||||||
static readonly ERR_DEPRECATED = "ERR_DEPRECATED";
|
|
||||||
static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
|
|
||||||
static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
|
|
||||||
static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
|
|
||||||
static readonly ERR_INVALID_URL = "ERR_INVALID_URL";
|
|
||||||
static readonly ERR_CANCELED = "ERR_CANCELED";
|
|
||||||
static readonly ECONNABORTED = "ECONNABORTED";
|
|
||||||
static readonly ETIMEDOUT = "ETIMEDOUT";
|
|
||||||
}
|
|
||||||
|
|
||||||
declare class CanceledError<T> extends AxiosError<T> {
|
|
||||||
}
|
|
||||||
|
|
||||||
declare class Axios {
|
|
||||||
constructor(config?: axios.AxiosRequestConfig);
|
|
||||||
defaults: axios.AxiosDefaults;
|
|
||||||
interceptors: {
|
|
||||||
request: axios.AxiosInterceptorManager<axios.InternalAxiosRequestConfig>;
|
|
||||||
response: axios.AxiosInterceptorManager<axios.AxiosResponse>;
|
|
||||||
};
|
|
||||||
getUri(config?: axios.AxiosRequestConfig): string;
|
|
||||||
request<T = any, R = axios.AxiosResponse<T>, D = any>(config: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
get<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
delete<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
head<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
options<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
post<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
put<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
patch<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
postForm<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
putForm<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
patchForm<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
}
|
|
||||||
|
|
||||||
declare enum HttpStatusCode {
|
|
||||||
Continue = 100,
|
|
||||||
SwitchingProtocols = 101,
|
|
||||||
Processing = 102,
|
|
||||||
EarlyHints = 103,
|
|
||||||
Ok = 200,
|
|
||||||
Created = 201,
|
|
||||||
Accepted = 202,
|
|
||||||
NonAuthoritativeInformation = 203,
|
|
||||||
NoContent = 204,
|
|
||||||
ResetContent = 205,
|
|
||||||
PartialContent = 206,
|
|
||||||
MultiStatus = 207,
|
|
||||||
AlreadyReported = 208,
|
|
||||||
ImUsed = 226,
|
|
||||||
MultipleChoices = 300,
|
|
||||||
MovedPermanently = 301,
|
|
||||||
Found = 302,
|
|
||||||
SeeOther = 303,
|
|
||||||
NotModified = 304,
|
|
||||||
UseProxy = 305,
|
|
||||||
Unused = 306,
|
|
||||||
TemporaryRedirect = 307,
|
|
||||||
PermanentRedirect = 308,
|
|
||||||
BadRequest = 400,
|
|
||||||
Unauthorized = 401,
|
|
||||||
PaymentRequired = 402,
|
|
||||||
Forbidden = 403,
|
|
||||||
NotFound = 404,
|
|
||||||
MethodNotAllowed = 405,
|
|
||||||
NotAcceptable = 406,
|
|
||||||
ProxyAuthenticationRequired = 407,
|
|
||||||
RequestTimeout = 408,
|
|
||||||
Conflict = 409,
|
|
||||||
Gone = 410,
|
|
||||||
LengthRequired = 411,
|
|
||||||
PreconditionFailed = 412,
|
|
||||||
PayloadTooLarge = 413,
|
|
||||||
UriTooLong = 414,
|
|
||||||
UnsupportedMediaType = 415,
|
|
||||||
RangeNotSatisfiable = 416,
|
|
||||||
ExpectationFailed = 417,
|
|
||||||
ImATeapot = 418,
|
|
||||||
MisdirectedRequest = 421,
|
|
||||||
UnprocessableEntity = 422,
|
|
||||||
Locked = 423,
|
|
||||||
FailedDependency = 424,
|
|
||||||
TooEarly = 425,
|
|
||||||
UpgradeRequired = 426,
|
|
||||||
PreconditionRequired = 428,
|
|
||||||
TooManyRequests = 429,
|
|
||||||
RequestHeaderFieldsTooLarge = 431,
|
|
||||||
UnavailableForLegalReasons = 451,
|
|
||||||
InternalServerError = 500,
|
|
||||||
NotImplemented = 501,
|
|
||||||
BadGateway = 502,
|
|
||||||
ServiceUnavailable = 503,
|
|
||||||
GatewayTimeout = 504,
|
|
||||||
HttpVersionNotSupported = 505,
|
|
||||||
VariantAlsoNegotiates = 506,
|
|
||||||
InsufficientStorage = 507,
|
|
||||||
LoopDetected = 508,
|
|
||||||
NotExtended = 510,
|
|
||||||
NetworkAuthenticationRequired = 511,
|
|
||||||
}
|
|
||||||
|
|
||||||
type InternalAxiosError<T = unknown, D = any> = AxiosError<T, D>;
|
|
||||||
|
|
||||||
declare namespace axios {
|
|
||||||
type AxiosError<T = unknown, D = any> = InternalAxiosError<T, D>;
|
|
||||||
|
|
||||||
type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & {
|
|
||||||
[Key in CommonRequestHeadersList]: AxiosHeaderValue;
|
|
||||||
} & {
|
|
||||||
'Content-Type': ContentType
|
|
||||||
}>;
|
|
||||||
|
|
||||||
type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
|
|
||||||
|
|
||||||
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
|
|
||||||
|
|
||||||
type RawCommonResponseHeaders = {
|
|
||||||
[Key in CommonResponseHeadersList]: AxiosHeaderValue;
|
|
||||||
} & {
|
|
||||||
"set-cookie": string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;
|
|
||||||
|
|
||||||
type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
|
|
||||||
|
|
||||||
interface AxiosRequestTransformer {
|
|
||||||
(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosResponseTransformer {
|
|
||||||
(this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosAdapter {
|
|
||||||
(config: InternalAxiosRequestConfig): AxiosPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosBasicCredentials {
|
|
||||||
username: string;
|
|
||||||
password: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosProxyConfig {
|
|
||||||
host: string;
|
|
||||||
port: number;
|
|
||||||
auth?: AxiosBasicCredentials;
|
|
||||||
protocol?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
type Method =
|
|
||||||
| 'get' | 'GET'
|
|
||||||
| 'delete' | 'DELETE'
|
|
||||||
| 'head' | 'HEAD'
|
|
||||||
| 'options' | 'OPTIONS'
|
|
||||||
| 'post' | 'POST'
|
|
||||||
| 'put' | 'PUT'
|
|
||||||
| 'patch' | 'PATCH'
|
|
||||||
| 'purge' | 'PURGE'
|
|
||||||
| 'link' | 'LINK'
|
|
||||||
| 'unlink' | 'UNLINK';
|
|
||||||
|
|
||||||
type ResponseType =
|
|
||||||
| 'arraybuffer'
|
|
||||||
| 'blob'
|
|
||||||
| 'document'
|
|
||||||
| 'json'
|
|
||||||
| 'text'
|
|
||||||
| 'stream';
|
|
||||||
|
|
||||||
type responseEncoding =
|
|
||||||
| 'ascii' | 'ASCII'
|
|
||||||
| 'ansi' | 'ANSI'
|
|
||||||
| 'binary' | 'BINARY'
|
|
||||||
| 'base64' | 'BASE64'
|
|
||||||
| 'base64url' | 'BASE64URL'
|
|
||||||
| 'hex' | 'HEX'
|
|
||||||
| 'latin1' | 'LATIN1'
|
|
||||||
| 'ucs-2' | 'UCS-2'
|
|
||||||
| 'ucs2' | 'UCS2'
|
|
||||||
| 'utf-8' | 'UTF-8'
|
|
||||||
| 'utf8' | 'UTF8'
|
|
||||||
| 'utf16le' | 'UTF16LE';
|
|
||||||
|
|
||||||
interface TransitionalOptions {
|
|
||||||
silentJSONParsing?: boolean;
|
|
||||||
forcedJSONParsing?: boolean;
|
|
||||||
clarifyTimeoutError?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface GenericAbortSignal {
|
|
||||||
readonly aborted: boolean;
|
|
||||||
onabort?: ((...args: any) => any) | null;
|
|
||||||
addEventListener?: (...args: any) => any;
|
|
||||||
removeEventListener?: (...args: any) => any;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FormDataVisitorHelpers {
|
|
||||||
defaultVisitor: SerializerVisitor;
|
|
||||||
convertValue: (value: any) => any;
|
|
||||||
isVisitable: (value: any) => boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SerializerVisitor {
|
|
||||||
(
|
|
||||||
this: GenericFormData,
|
|
||||||
value: any,
|
|
||||||
key: string | number,
|
|
||||||
path: null | Array<string | number>,
|
|
||||||
helpers: FormDataVisitorHelpers
|
|
||||||
): boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SerializerOptions {
|
|
||||||
visitor?: SerializerVisitor;
|
|
||||||
dots?: boolean;
|
|
||||||
metaTokens?: boolean;
|
|
||||||
indexes?: boolean | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// tslint:disable-next-line
|
|
||||||
interface FormSerializerOptions extends SerializerOptions {
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ParamEncoder {
|
|
||||||
(value: any, defaultEncoder: (value: any) => any): any;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CustomParamsSerializer {
|
|
||||||
(params: Record<string, any>, options?: ParamsSerializerOptions): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ParamsSerializerOptions extends SerializerOptions {
|
|
||||||
encode?: ParamEncoder;
|
|
||||||
serialize?: CustomParamsSerializer;
|
|
||||||
}
|
|
||||||
|
|
||||||
type MaxUploadRate = number;
|
|
||||||
|
|
||||||
type MaxDownloadRate = number;
|
|
||||||
|
|
||||||
type BrowserProgressEvent = any;
|
|
||||||
|
|
||||||
interface AxiosProgressEvent {
|
|
||||||
loaded: number;
|
|
||||||
total?: number;
|
|
||||||
progress?: number;
|
|
||||||
bytes: number;
|
|
||||||
rate?: number;
|
|
||||||
estimated?: number;
|
|
||||||
upload?: boolean;
|
|
||||||
download?: boolean;
|
|
||||||
event?: BrowserProgressEvent;
|
|
||||||
}
|
|
||||||
|
|
||||||
type Milliseconds = number;
|
|
||||||
|
|
||||||
type AxiosAdapterName = 'xhr' | 'http' | string;
|
|
||||||
|
|
||||||
type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;
|
|
||||||
|
|
||||||
type AddressFamily = 4 | 6 | undefined;
|
|
||||||
|
|
||||||
interface LookupAddressEntry {
|
|
||||||
address: string;
|
|
||||||
family?: AddressFamily;
|
|
||||||
}
|
|
||||||
|
|
||||||
type LookupAddress = string | LookupAddressEntry;
|
|
||||||
|
|
||||||
interface AxiosRequestConfig<D = any> {
|
|
||||||
url?: string;
|
|
||||||
method?: Method | string;
|
|
||||||
baseURL?: string;
|
|
||||||
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
|
|
||||||
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
|
|
||||||
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
|
|
||||||
params?: any;
|
|
||||||
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
|
|
||||||
data?: D;
|
|
||||||
timeout?: Milliseconds;
|
|
||||||
timeoutErrorMessage?: string;
|
|
||||||
withCredentials?: boolean;
|
|
||||||
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
|
|
||||||
auth?: AxiosBasicCredentials;
|
|
||||||
responseType?: ResponseType;
|
|
||||||
responseEncoding?: responseEncoding | string;
|
|
||||||
xsrfCookieName?: string;
|
|
||||||
xsrfHeaderName?: string;
|
|
||||||
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
|
||||||
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
|
||||||
maxContentLength?: number;
|
|
||||||
validateStatus?: ((status: number) => boolean) | null;
|
|
||||||
maxBodyLength?: number;
|
|
||||||
maxRedirects?: number;
|
|
||||||
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
|
|
||||||
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>, statusCode: HttpStatusCode}) => void;
|
|
||||||
socketPath?: string | null;
|
|
||||||
transport?: any;
|
|
||||||
httpAgent?: any;
|
|
||||||
httpsAgent?: any;
|
|
||||||
proxy?: AxiosProxyConfig | false;
|
|
||||||
cancelToken?: CancelToken;
|
|
||||||
decompress?: boolean;
|
|
||||||
transitional?: TransitionalOptions;
|
|
||||||
signal?: GenericAbortSignal;
|
|
||||||
insecureHTTPParser?: boolean;
|
|
||||||
env?: {
|
|
||||||
FormData?: new (...args: any[]) => object;
|
|
||||||
};
|
|
||||||
formSerializer?: FormSerializerOptions;
|
|
||||||
family?: AddressFamily;
|
|
||||||
lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) |
|
|
||||||
((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>);
|
|
||||||
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Alias
|
|
||||||
type RawAxiosRequestConfig<D = any> = AxiosRequestConfig<D>;
|
|
||||||
|
|
||||||
interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig {
|
|
||||||
headers: AxiosRequestHeaders;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface HeadersDefaults {
|
|
||||||
common: RawAxiosRequestHeaders;
|
|
||||||
delete: RawAxiosRequestHeaders;
|
|
||||||
get: RawAxiosRequestHeaders;
|
|
||||||
head: RawAxiosRequestHeaders;
|
|
||||||
post: RawAxiosRequestHeaders;
|
|
||||||
put: RawAxiosRequestHeaders;
|
|
||||||
patch: RawAxiosRequestHeaders;
|
|
||||||
options?: RawAxiosRequestHeaders;
|
|
||||||
purge?: RawAxiosRequestHeaders;
|
|
||||||
link?: RawAxiosRequestHeaders;
|
|
||||||
unlink?: RawAxiosRequestHeaders;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
|
|
||||||
headers: HeadersDefaults;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
|
|
||||||
headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosResponse<T = any, D = any> {
|
|
||||||
data: T;
|
|
||||||
status: number;
|
|
||||||
statusText: string;
|
|
||||||
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
|
|
||||||
config: InternalAxiosRequestConfig<D>;
|
|
||||||
request?: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
type AxiosPromise<T = any> = Promise<AxiosResponse<T>>;
|
|
||||||
|
|
||||||
interface CancelStatic {
|
|
||||||
new (message?: string): Cancel;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Cancel {
|
|
||||||
message: string | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Canceler {
|
|
||||||
(message?: string, config?: AxiosRequestConfig, request?: any): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CancelTokenStatic {
|
|
||||||
new (executor: (cancel: Canceler) => void): CancelToken;
|
|
||||||
source(): CancelTokenSource;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CancelToken {
|
|
||||||
promise: Promise<Cancel>;
|
|
||||||
reason?: Cancel;
|
|
||||||
throwIfRequested(): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CancelTokenSource {
|
|
||||||
token: CancelToken;
|
|
||||||
cancel: Canceler;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosInterceptorOptions {
|
|
||||||
synchronous?: boolean;
|
|
||||||
runWhen?: (config: InternalAxiosRequestConfig) => boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosInterceptorManager<V> {
|
|
||||||
use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any, options?: AxiosInterceptorOptions): number;
|
|
||||||
eject(id: number): void;
|
|
||||||
clear(): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosInstance extends Axios {
|
|
||||||
<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
|
|
||||||
defaults: Omit<AxiosDefaults, 'headers'> & {
|
|
||||||
headers: HeadersDefaults & {
|
|
||||||
[key: string]: AxiosHeaderValue
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface GenericFormData {
|
|
||||||
append(name: string, value: any, options?: any): any;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface GenericHTMLFormElement {
|
|
||||||
name: string;
|
|
||||||
method: string;
|
|
||||||
submit(): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AxiosStatic extends AxiosInstance {
|
|
||||||
create(config?: CreateAxiosDefaults): AxiosInstance;
|
|
||||||
Cancel: CancelStatic;
|
|
||||||
CancelToken: CancelTokenStatic;
|
|
||||||
Axios: typeof Axios;
|
|
||||||
AxiosError: typeof AxiosError;
|
|
||||||
CanceledError: typeof CanceledError;
|
|
||||||
HttpStatusCode: typeof HttpStatusCode;
|
|
||||||
readonly VERSION: string;
|
|
||||||
isCancel(value: any): value is Cancel;
|
|
||||||
all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
|
|
||||||
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
|
|
||||||
isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
|
|
||||||
toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
|
|
||||||
formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
|
|
||||||
getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;
|
|
||||||
AxiosHeaders: typeof AxiosHeaders;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
declare const axios: axios.AxiosStatic;
|
|
||||||
|
|
||||||
export = axios;
|
|
|
@ -1,116 +1,9 @@
|
||||||
// TypeScript Version: 4.7
|
export interface AxiosTransformer {
|
||||||
export type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
|
(data: any, headers?: any): any;
|
||||||
|
|
||||||
interface RawAxiosHeaders {
|
|
||||||
[key: string]: AxiosHeaderValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
type MethodsHeaders = Partial<{
|
|
||||||
[Key in Method as Lowercase<Key>]: AxiosHeaders;
|
|
||||||
} & {common: AxiosHeaders}>;
|
|
||||||
|
|
||||||
type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean);
|
|
||||||
|
|
||||||
type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any;
|
|
||||||
|
|
||||||
export class AxiosHeaders {
|
|
||||||
constructor(
|
|
||||||
headers?: RawAxiosHeaders | AxiosHeaders | string
|
|
||||||
);
|
|
||||||
|
|
||||||
[key: string]: any;
|
|
||||||
|
|
||||||
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
|
|
||||||
|
|
||||||
get(headerName: string, parser: RegExp): RegExpExecArray | null;
|
|
||||||
get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
|
|
||||||
|
|
||||||
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
clear(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
normalize(format: boolean): AxiosHeaders;
|
|
||||||
|
|
||||||
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
|
|
||||||
|
|
||||||
toJSON(asStrings?: boolean): RawAxiosHeaders;
|
|
||||||
|
|
||||||
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
|
|
||||||
|
|
||||||
static accessor(header: string | string[]): AxiosHeaders;
|
|
||||||
|
|
||||||
static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
|
|
||||||
|
|
||||||
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getContentType(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
|
|
||||||
hasContentType(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getContentLength(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
|
|
||||||
hasContentLength(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getAccept(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
|
|
||||||
hasAccept(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getUserAgent(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
|
|
||||||
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getContentEncoding(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
|
|
||||||
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
|
||||||
getAuthorization(parser?: RegExp): RegExpExecArray | null;
|
|
||||||
getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
|
|
||||||
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;
|
|
||||||
|
|
||||||
[Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>;
|
|
||||||
}
|
|
||||||
|
|
||||||
type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent' | 'Content-Encoding' | 'Authorization';
|
|
||||||
|
|
||||||
type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';
|
|
||||||
|
|
||||||
export type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & {
|
|
||||||
[Key in CommonRequestHeadersList]: AxiosHeaderValue;
|
|
||||||
} & {
|
|
||||||
'Content-Type': ContentType
|
|
||||||
}>;
|
|
||||||
|
|
||||||
export type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
|
|
||||||
|
|
||||||
type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control'| 'Content-Encoding';
|
|
||||||
|
|
||||||
type RawCommonResponseHeaders = {
|
|
||||||
[Key in CommonResponseHeadersList]: AxiosHeaderValue;
|
|
||||||
} & {
|
|
||||||
"set-cookie": string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;
|
|
||||||
|
|
||||||
export type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
|
|
||||||
|
|
||||||
export interface AxiosRequestTransformer {
|
|
||||||
(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AxiosResponseTransformer {
|
|
||||||
(this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AxiosAdapter {
|
export interface AxiosAdapter {
|
||||||
(config: InternalAxiosRequestConfig): AxiosPromise;
|
(config: AxiosRequestConfig): AxiosPromise<any>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AxiosBasicCredentials {
|
export interface AxiosBasicCredentials {
|
||||||
|
@ -121,335 +14,103 @@ export interface AxiosBasicCredentials {
|
||||||
export interface AxiosProxyConfig {
|
export interface AxiosProxyConfig {
|
||||||
host: string;
|
host: string;
|
||||||
port: number;
|
port: number;
|
||||||
auth?: AxiosBasicCredentials;
|
auth?: {
|
||||||
|
username: string;
|
||||||
|
password:string;
|
||||||
|
};
|
||||||
protocol?: string;
|
protocol?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum HttpStatusCode {
|
|
||||||
Continue = 100,
|
|
||||||
SwitchingProtocols = 101,
|
|
||||||
Processing = 102,
|
|
||||||
EarlyHints = 103,
|
|
||||||
Ok = 200,
|
|
||||||
Created = 201,
|
|
||||||
Accepted = 202,
|
|
||||||
NonAuthoritativeInformation = 203,
|
|
||||||
NoContent = 204,
|
|
||||||
ResetContent = 205,
|
|
||||||
PartialContent = 206,
|
|
||||||
MultiStatus = 207,
|
|
||||||
AlreadyReported = 208,
|
|
||||||
ImUsed = 226,
|
|
||||||
MultipleChoices = 300,
|
|
||||||
MovedPermanently = 301,
|
|
||||||
Found = 302,
|
|
||||||
SeeOther = 303,
|
|
||||||
NotModified = 304,
|
|
||||||
UseProxy = 305,
|
|
||||||
Unused = 306,
|
|
||||||
TemporaryRedirect = 307,
|
|
||||||
PermanentRedirect = 308,
|
|
||||||
BadRequest = 400,
|
|
||||||
Unauthorized = 401,
|
|
||||||
PaymentRequired = 402,
|
|
||||||
Forbidden = 403,
|
|
||||||
NotFound = 404,
|
|
||||||
MethodNotAllowed = 405,
|
|
||||||
NotAcceptable = 406,
|
|
||||||
ProxyAuthenticationRequired = 407,
|
|
||||||
RequestTimeout = 408,
|
|
||||||
Conflict = 409,
|
|
||||||
Gone = 410,
|
|
||||||
LengthRequired = 411,
|
|
||||||
PreconditionFailed = 412,
|
|
||||||
PayloadTooLarge = 413,
|
|
||||||
UriTooLong = 414,
|
|
||||||
UnsupportedMediaType = 415,
|
|
||||||
RangeNotSatisfiable = 416,
|
|
||||||
ExpectationFailed = 417,
|
|
||||||
ImATeapot = 418,
|
|
||||||
MisdirectedRequest = 421,
|
|
||||||
UnprocessableEntity = 422,
|
|
||||||
Locked = 423,
|
|
||||||
FailedDependency = 424,
|
|
||||||
TooEarly = 425,
|
|
||||||
UpgradeRequired = 426,
|
|
||||||
PreconditionRequired = 428,
|
|
||||||
TooManyRequests = 429,
|
|
||||||
RequestHeaderFieldsTooLarge = 431,
|
|
||||||
UnavailableForLegalReasons = 451,
|
|
||||||
InternalServerError = 500,
|
|
||||||
NotImplemented = 501,
|
|
||||||
BadGateway = 502,
|
|
||||||
ServiceUnavailable = 503,
|
|
||||||
GatewayTimeout = 504,
|
|
||||||
HttpVersionNotSupported = 505,
|
|
||||||
VariantAlsoNegotiates = 506,
|
|
||||||
InsufficientStorage = 507,
|
|
||||||
LoopDetected = 508,
|
|
||||||
NotExtended = 510,
|
|
||||||
NetworkAuthenticationRequired = 511,
|
|
||||||
}
|
|
||||||
|
|
||||||
export type Method =
|
export type Method =
|
||||||
| 'get' | 'GET'
|
| 'get' | 'GET'
|
||||||
| 'delete' | 'DELETE'
|
| 'delete' | 'DELETE'
|
||||||
| 'head' | 'HEAD'
|
| 'head' | 'HEAD'
|
||||||
| 'options' | 'OPTIONS'
|
| 'options' | 'OPTIONS'
|
||||||
| 'post' | 'POST'
|
| 'post' | 'POST'
|
||||||
| 'put' | 'PUT'
|
| 'put' | 'PUT'
|
||||||
| 'patch' | 'PATCH'
|
| 'patch' | 'PATCH'
|
||||||
| 'purge' | 'PURGE'
|
| 'purge' | 'PURGE'
|
||||||
| 'link' | 'LINK'
|
| 'link' | 'LINK'
|
||||||
| 'unlink' | 'UNLINK';
|
| 'unlink' | 'UNLINK'
|
||||||
|
|
||||||
export type ResponseType =
|
export type ResponseType =
|
||||||
| 'arraybuffer'
|
| 'arraybuffer'
|
||||||
| 'blob'
|
| 'blob'
|
||||||
| 'document'
|
| 'document'
|
||||||
| 'json'
|
| 'json'
|
||||||
| 'text'
|
| 'text'
|
||||||
| 'stream';
|
| 'stream'
|
||||||
|
|
||||||
export type responseEncoding =
|
export interface TransitionalOptions{
|
||||||
| 'ascii' | 'ASCII'
|
silentJSONParsing: boolean;
|
||||||
| 'ansi' | 'ANSI'
|
forcedJSONParsing: boolean;
|
||||||
| 'binary' | 'BINARY'
|
clarifyTimeoutError: boolean;
|
||||||
| 'base64' | 'BASE64'
|
|
||||||
| 'base64url' | 'BASE64URL'
|
|
||||||
| 'hex' | 'HEX'
|
|
||||||
| 'latin1' | 'LATIN1'
|
|
||||||
| 'ucs-2' | 'UCS-2'
|
|
||||||
| 'ucs2' | 'UCS2'
|
|
||||||
| 'utf-8' | 'UTF-8'
|
|
||||||
| 'utf8' | 'UTF8'
|
|
||||||
| 'utf16le' | 'UTF16LE';
|
|
||||||
|
|
||||||
export interface TransitionalOptions {
|
|
||||||
silentJSONParsing?: boolean;
|
|
||||||
forcedJSONParsing?: boolean;
|
|
||||||
clarifyTimeoutError?: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GenericAbortSignal {
|
export interface AxiosRequestConfig {
|
||||||
readonly aborted: boolean;
|
|
||||||
onabort?: ((...args: any) => any) | null;
|
|
||||||
addEventListener?: (...args: any) => any;
|
|
||||||
removeEventListener?: (...args: any) => any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface FormDataVisitorHelpers {
|
|
||||||
defaultVisitor: SerializerVisitor;
|
|
||||||
convertValue: (value: any) => any;
|
|
||||||
isVisitable: (value: any) => boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SerializerVisitor {
|
|
||||||
(
|
|
||||||
this: GenericFormData,
|
|
||||||
value: any,
|
|
||||||
key: string | number,
|
|
||||||
path: null | Array<string | number>,
|
|
||||||
helpers: FormDataVisitorHelpers
|
|
||||||
): boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SerializerOptions {
|
|
||||||
visitor?: SerializerVisitor;
|
|
||||||
dots?: boolean;
|
|
||||||
metaTokens?: boolean;
|
|
||||||
indexes?: boolean | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// tslint:disable-next-line
|
|
||||||
export interface FormSerializerOptions extends SerializerOptions {
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ParamEncoder {
|
|
||||||
(value: any, defaultEncoder: (value: any) => any): any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CustomParamsSerializer {
|
|
||||||
(params: Record<string, any>, options?: ParamsSerializerOptions): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ParamsSerializerOptions extends SerializerOptions {
|
|
||||||
encode?: ParamEncoder;
|
|
||||||
serialize?: CustomParamsSerializer;
|
|
||||||
}
|
|
||||||
|
|
||||||
type MaxUploadRate = number;
|
|
||||||
|
|
||||||
type MaxDownloadRate = number;
|
|
||||||
|
|
||||||
type BrowserProgressEvent = any;
|
|
||||||
|
|
||||||
export interface AxiosProgressEvent {
|
|
||||||
loaded: number;
|
|
||||||
total?: number;
|
|
||||||
progress?: number;
|
|
||||||
bytes: number;
|
|
||||||
rate?: number;
|
|
||||||
estimated?: number;
|
|
||||||
upload?: boolean;
|
|
||||||
download?: boolean;
|
|
||||||
event?: BrowserProgressEvent;
|
|
||||||
}
|
|
||||||
|
|
||||||
type Milliseconds = number;
|
|
||||||
|
|
||||||
type AxiosAdapterName = 'xhr' | 'http' | string;
|
|
||||||
|
|
||||||
type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;
|
|
||||||
|
|
||||||
export type AddressFamily = 4 | 6 | undefined;
|
|
||||||
|
|
||||||
export interface LookupAddressEntry {
|
|
||||||
address: string;
|
|
||||||
family?: AddressFamily;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type LookupAddress = string | LookupAddressEntry;
|
|
||||||
|
|
||||||
export interface AxiosRequestConfig<D = any> {
|
|
||||||
url?: string;
|
url?: string;
|
||||||
method?: Method | string;
|
method?: Method;
|
||||||
baseURL?: string;
|
baseURL?: string;
|
||||||
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
|
transformRequest?: AxiosTransformer | AxiosTransformer[];
|
||||||
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
|
transformResponse?: AxiosTransformer | AxiosTransformer[];
|
||||||
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
|
headers?: any;
|
||||||
params?: any;
|
params?: any;
|
||||||
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
|
paramsSerializer?: (params: any) => string;
|
||||||
data?: D;
|
data?: any;
|
||||||
timeout?: Milliseconds;
|
timeout?: number;
|
||||||
timeoutErrorMessage?: string;
|
timeoutErrorMessage?: string;
|
||||||
withCredentials?: boolean;
|
withCredentials?: boolean;
|
||||||
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
|
adapter?: AxiosAdapter;
|
||||||
auth?: AxiosBasicCredentials;
|
auth?: AxiosBasicCredentials;
|
||||||
responseType?: ResponseType;
|
responseType?: ResponseType;
|
||||||
responseEncoding?: responseEncoding | string;
|
|
||||||
xsrfCookieName?: string;
|
xsrfCookieName?: string;
|
||||||
xsrfHeaderName?: string;
|
xsrfHeaderName?: string;
|
||||||
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
onUploadProgress?: (progressEvent: any) => void;
|
||||||
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
onDownloadProgress?: (progressEvent: any) => void;
|
||||||
maxContentLength?: number;
|
maxContentLength?: number;
|
||||||
validateStatus?: ((status: number) => boolean) | null;
|
validateStatus?: ((status: number) => boolean) | null;
|
||||||
maxBodyLength?: number;
|
maxBodyLength?: number;
|
||||||
maxRedirects?: number;
|
maxRedirects?: number;
|
||||||
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
|
|
||||||
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>, statusCode: HttpStatusCode}) => void;
|
|
||||||
socketPath?: string | null;
|
socketPath?: string | null;
|
||||||
transport?: any;
|
|
||||||
httpAgent?: any;
|
httpAgent?: any;
|
||||||
httpsAgent?: any;
|
httpsAgent?: any;
|
||||||
proxy?: AxiosProxyConfig | false;
|
proxy?: AxiosProxyConfig | false;
|
||||||
cancelToken?: CancelToken;
|
cancelToken?: CancelToken;
|
||||||
decompress?: boolean;
|
decompress?: boolean;
|
||||||
transitional?: TransitionalOptions;
|
transitional?: TransitionalOptions
|
||||||
signal?: GenericAbortSignal;
|
|
||||||
insecureHTTPParser?: boolean;
|
|
||||||
env?: {
|
|
||||||
FormData?: new (...args: any[]) => object;
|
|
||||||
};
|
|
||||||
formSerializer?: FormSerializerOptions;
|
|
||||||
family?: AddressFamily;
|
|
||||||
lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) |
|
|
||||||
((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>);
|
|
||||||
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Alias
|
export interface AxiosResponse<T = any> {
|
||||||
export type RawAxiosRequestConfig<D = any> = AxiosRequestConfig<D>;
|
|
||||||
|
|
||||||
export interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> {
|
|
||||||
headers: AxiosRequestHeaders;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HeadersDefaults {
|
|
||||||
common: RawAxiosRequestHeaders;
|
|
||||||
delete: RawAxiosRequestHeaders;
|
|
||||||
get: RawAxiosRequestHeaders;
|
|
||||||
head: RawAxiosRequestHeaders;
|
|
||||||
post: RawAxiosRequestHeaders;
|
|
||||||
put: RawAxiosRequestHeaders;
|
|
||||||
patch: RawAxiosRequestHeaders;
|
|
||||||
options?: RawAxiosRequestHeaders;
|
|
||||||
purge?: RawAxiosRequestHeaders;
|
|
||||||
link?: RawAxiosRequestHeaders;
|
|
||||||
unlink?: RawAxiosRequestHeaders;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
|
|
||||||
headers: HeadersDefaults;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
|
|
||||||
headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AxiosResponse<T = any, D = any> {
|
|
||||||
data: T;
|
data: T;
|
||||||
status: number;
|
status: number;
|
||||||
statusText: string;
|
statusText: string;
|
||||||
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
|
headers: any;
|
||||||
config: InternalAxiosRequestConfig<D>;
|
config: AxiosRequestConfig;
|
||||||
request?: any;
|
request?: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class AxiosError<T = unknown, D = any> extends Error {
|
export interface AxiosError<T = any> extends Error {
|
||||||
constructor(
|
config: AxiosRequestConfig;
|
||||||
message?: string,
|
|
||||||
code?: string,
|
|
||||||
config?: InternalAxiosRequestConfig<D>,
|
|
||||||
request?: any,
|
|
||||||
response?: AxiosResponse<T, D>
|
|
||||||
);
|
|
||||||
|
|
||||||
config?: InternalAxiosRequestConfig<D>;
|
|
||||||
code?: string;
|
code?: string;
|
||||||
request?: any;
|
request?: any;
|
||||||
response?: AxiosResponse<T, D>;
|
response?: AxiosResponse<T>;
|
||||||
isAxiosError: boolean;
|
isAxiosError: boolean;
|
||||||
status?: number;
|
|
||||||
toJSON: () => object;
|
toJSON: () => object;
|
||||||
cause?: Error;
|
|
||||||
static from<T = unknown, D = any>(
|
|
||||||
error: Error | unknown,
|
|
||||||
code?: string,
|
|
||||||
config?: InternalAxiosRequestConfig<D>,
|
|
||||||
request?: any,
|
|
||||||
response?: AxiosResponse<T, D>,
|
|
||||||
customProps?: object,
|
|
||||||
): AxiosError<T, D>;
|
|
||||||
static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
|
|
||||||
static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
|
|
||||||
static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";
|
|
||||||
static readonly ERR_NETWORK = "ERR_NETWORK";
|
|
||||||
static readonly ERR_DEPRECATED = "ERR_DEPRECATED";
|
|
||||||
static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
|
|
||||||
static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
|
|
||||||
static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
|
|
||||||
static readonly ERR_INVALID_URL = "ERR_INVALID_URL";
|
|
||||||
static readonly ERR_CANCELED = "ERR_CANCELED";
|
|
||||||
static readonly ECONNABORTED = "ECONNABORTED";
|
|
||||||
static readonly ETIMEDOUT = "ETIMEDOUT";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CanceledError<T> extends AxiosError<T> {
|
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AxiosPromise<T = any> = Promise<AxiosResponse<T>>;
|
|
||||||
|
|
||||||
export interface CancelStatic {
|
export interface CancelStatic {
|
||||||
new (message?: string): Cancel;
|
new (message?: string): Cancel;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Cancel {
|
export interface Cancel {
|
||||||
message: string | undefined;
|
message: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Canceler {
|
export interface Canceler {
|
||||||
(message?: string, config?: AxiosRequestConfig, request?: any): void;
|
(message?: string): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CancelTokenStatic {
|
export interface CancelTokenStatic {
|
||||||
|
@ -468,90 +129,38 @@ export interface CancelTokenSource {
|
||||||
cancel: Canceler;
|
cancel: Canceler;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AxiosInterceptorOptions {
|
|
||||||
synchronous?: boolean;
|
|
||||||
runWhen?: (config: InternalAxiosRequestConfig) => boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AxiosInterceptorManager<V> {
|
export interface AxiosInterceptorManager<V> {
|
||||||
use(onFulfilled?: ((value: V) => V | Promise<V>) | null, onRejected?: ((error: any) => any) | null, options?: AxiosInterceptorOptions): number;
|
use<T = V>(onFulfilled?: (value: V) => T | Promise<T>, onRejected?: (error: any) => any): number;
|
||||||
eject(id: number): void;
|
eject(id: number): void;
|
||||||
clear(): void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Axios {
|
export interface AxiosInstance {
|
||||||
constructor(config?: AxiosRequestConfig);
|
(config: AxiosRequestConfig): AxiosPromise;
|
||||||
defaults: AxiosDefaults;
|
(url: string, config?: AxiosRequestConfig): AxiosPromise;
|
||||||
|
defaults: AxiosRequestConfig;
|
||||||
interceptors: {
|
interceptors: {
|
||||||
request: AxiosInterceptorManager<InternalAxiosRequestConfig>;
|
request: AxiosInterceptorManager<AxiosRequestConfig>;
|
||||||
response: AxiosInterceptorManager<AxiosResponse>;
|
response: AxiosInterceptorManager<AxiosResponse>;
|
||||||
};
|
};
|
||||||
getUri(config?: AxiosRequestConfig): string;
|
getUri(config?: AxiosRequestConfig): string;
|
||||||
request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
|
request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>;
|
||||||
get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
|
get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||||
delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
|
delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||||
head<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
|
head<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||||
options<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
|
options<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||||
post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
|
post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
|
||||||
put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
|
put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
|
||||||
patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
|
patch<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
|
||||||
postForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
putForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
patchForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AxiosInstance extends Axios {
|
|
||||||
<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
|
|
||||||
|
|
||||||
defaults: Omit<AxiosDefaults, 'headers'> & {
|
|
||||||
headers: HeadersDefaults & {
|
|
||||||
[key: string]: AxiosHeaderValue
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GenericFormData {
|
|
||||||
append(name: string, value: any, options?: any): any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GenericHTMLFormElement {
|
|
||||||
name: string;
|
|
||||||
method: string;
|
|
||||||
submit(): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;
|
|
||||||
|
|
||||||
export function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
|
|
||||||
|
|
||||||
export function formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
|
|
||||||
|
|
||||||
export function isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
|
|
||||||
|
|
||||||
export function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
|
|
||||||
|
|
||||||
export function isCancel(value: any): value is Cancel;
|
|
||||||
|
|
||||||
export function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
|
|
||||||
|
|
||||||
export interface AxiosStatic extends AxiosInstance {
|
export interface AxiosStatic extends AxiosInstance {
|
||||||
create(config?: CreateAxiosDefaults): AxiosInstance;
|
create(config?: AxiosRequestConfig): AxiosInstance;
|
||||||
Cancel: CancelStatic;
|
Cancel: CancelStatic;
|
||||||
CancelToken: CancelTokenStatic;
|
CancelToken: CancelTokenStatic;
|
||||||
Axios: typeof Axios;
|
isCancel(value: any): boolean;
|
||||||
AxiosError: typeof AxiosError;
|
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
|
||||||
HttpStatusCode: typeof HttpStatusCode;
|
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
|
||||||
readonly VERSION: string;
|
isAxiosError(payload: any): payload is AxiosError;
|
||||||
isCancel: typeof isCancel;
|
|
||||||
all: typeof all;
|
|
||||||
spread: typeof spread;
|
|
||||||
isAxiosError: typeof isAxiosError;
|
|
||||||
toFormData: typeof toFormData;
|
|
||||||
formToJSON: typeof formToJSON;
|
|
||||||
getAdapter: typeof getAdapter;
|
|
||||||
CanceledError: typeof CanceledError;
|
|
||||||
AxiosHeaders: typeof AxiosHeaders;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
declare const axios: AxiosStatic;
|
declare const axios: AxiosStatic;
|
||||||
|
|
|
@ -1,43 +1 @@
|
||||||
import axios from './lib/axios.js';
|
module.exports = require('./lib/axios');
|
||||||
|
|
||||||
// This module is intended to unwrap Axios default export as named.
|
|
||||||
// Keep top-level export same with static properties
|
|
||||||
// so that it can keep same with es module or cjs
|
|
||||||
const {
|
|
||||||
Axios,
|
|
||||||
AxiosError,
|
|
||||||
CanceledError,
|
|
||||||
isCancel,
|
|
||||||
CancelToken,
|
|
||||||
VERSION,
|
|
||||||
all,
|
|
||||||
Cancel,
|
|
||||||
isAxiosError,
|
|
||||||
spread,
|
|
||||||
toFormData,
|
|
||||||
AxiosHeaders,
|
|
||||||
HttpStatusCode,
|
|
||||||
formToJSON,
|
|
||||||
getAdapter,
|
|
||||||
mergeConfig
|
|
||||||
} = axios;
|
|
||||||
|
|
||||||
export {
|
|
||||||
axios as default,
|
|
||||||
Axios,
|
|
||||||
AxiosError,
|
|
||||||
CanceledError,
|
|
||||||
isCancel,
|
|
||||||
CancelToken,
|
|
||||||
VERSION,
|
|
||||||
all,
|
|
||||||
Cancel,
|
|
||||||
isAxiosError,
|
|
||||||
spread,
|
|
||||||
toFormData,
|
|
||||||
AxiosHeaders,
|
|
||||||
HttpStatusCode,
|
|
||||||
formToJSON,
|
|
||||||
getAdapter,
|
|
||||||
mergeConfig
|
|
||||||
}
|
|
|
@ -1,77 +0,0 @@
|
||||||
import utils from '../utils.js';
|
|
||||||
import httpAdapter from './http.js';
|
|
||||||
import xhrAdapter from './xhr.js';
|
|
||||||
import AxiosError from "../core/AxiosError.js";
|
|
||||||
|
|
||||||
const knownAdapters = {
|
|
||||||
http: httpAdapter,
|
|
||||||
xhr: xhrAdapter
|
|
||||||
}
|
|
||||||
|
|
||||||
utils.forEach(knownAdapters, (fn, value) => {
|
|
||||||
if (fn) {
|
|
||||||
try {
|
|
||||||
Object.defineProperty(fn, 'name', {value});
|
|
||||||
} catch (e) {
|
|
||||||
// eslint-disable-next-line no-empty
|
|
||||||
}
|
|
||||||
Object.defineProperty(fn, 'adapterName', {value});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const renderReason = (reason) => `- ${reason}`;
|
|
||||||
|
|
||||||
const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;
|
|
||||||
|
|
||||||
export default {
|
|
||||||
getAdapter: (adapters) => {
|
|
||||||
adapters = utils.isArray(adapters) ? adapters : [adapters];
|
|
||||||
|
|
||||||
const {length} = adapters;
|
|
||||||
let nameOrAdapter;
|
|
||||||
let adapter;
|
|
||||||
|
|
||||||
const rejectedReasons = {};
|
|
||||||
|
|
||||||
for (let i = 0; i < length; i++) {
|
|
||||||
nameOrAdapter = adapters[i];
|
|
||||||
let id;
|
|
||||||
|
|
||||||
adapter = nameOrAdapter;
|
|
||||||
|
|
||||||
if (!isResolvedHandle(nameOrAdapter)) {
|
|
||||||
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
|
|
||||||
|
|
||||||
if (adapter === undefined) {
|
|
||||||
throw new AxiosError(`Unknown adapter '${id}'`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (adapter) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
rejectedReasons[id || '#' + i] = adapter;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!adapter) {
|
|
||||||
|
|
||||||
const reasons = Object.entries(rejectedReasons)
|
|
||||||
.map(([id, state]) => `adapter ${id} ` +
|
|
||||||
(state === false ? 'is not supported by the environment' : 'is not available in the build')
|
|
||||||
);
|
|
||||||
|
|
||||||
let s = length ?
|
|
||||||
(reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
|
|
||||||
'as no adapter specified';
|
|
||||||
|
|
||||||
throw new AxiosError(
|
|
||||||
`There is no suitable adapter to dispatch the request ` + s,
|
|
||||||
'ERR_NOT_SUPPORT'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return adapter;
|
|
||||||
},
|
|
||||||
adapters: knownAdapters
|
|
||||||
}
|
|
|
@ -1,316 +1,73 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import utils from './../utils.js';
|
var utils = require('./../utils');
|
||||||
import settle from './../core/settle.js';
|
var settle = require('./../core/settle');
|
||||||
import buildFullPath from '../core/buildFullPath.js';
|
var buildFullPath = require('../core/buildFullPath');
|
||||||
import buildURL from './../helpers/buildURL.js';
|
var buildURL = require('./../helpers/buildURL');
|
||||||
import {getProxyForUrl} from 'proxy-from-env';
|
var http = require('http');
|
||||||
import http from 'http';
|
var https = require('https');
|
||||||
import https from 'https';
|
var httpFollow = require('follow-redirects').http;
|
||||||
import util from 'util';
|
var httpsFollow = require('follow-redirects').https;
|
||||||
import followRedirects from 'follow-redirects';
|
var url = require('url');
|
||||||
import zlib from 'zlib';
|
var zlib = require('zlib');
|
||||||
import {VERSION} from '../env/data.js';
|
var pkg = require('./../../package.json');
|
||||||
import transitionalDefaults from '../defaults/transitional.js';
|
var createError = require('../core/createError');
|
||||||
import AxiosError from '../core/AxiosError.js';
|
var enhanceError = require('../core/enhanceError');
|
||||||
import CanceledError from '../cancel/CanceledError.js';
|
|
||||||
import platform from '../platform/index.js';
|
|
||||||
import fromDataURI from '../helpers/fromDataURI.js';
|
|
||||||
import stream from 'stream';
|
|
||||||
import AxiosHeaders from '../core/AxiosHeaders.js';
|
|
||||||
import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
|
|
||||||
import EventEmitter from 'events';
|
|
||||||
import formDataToStream from "../helpers/formDataToStream.js";
|
|
||||||
import readBlob from "../helpers/readBlob.js";
|
|
||||||
import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js';
|
|
||||||
import callbackify from "../helpers/callbackify.js";
|
|
||||||
|
|
||||||
const zlibOptions = {
|
var isHttps = /https:?/;
|
||||||
flush: zlib.constants.Z_SYNC_FLUSH,
|
|
||||||
finishFlush: zlib.constants.Z_SYNC_FLUSH
|
|
||||||
};
|
|
||||||
|
|
||||||
const brotliOptions = {
|
|
||||||
flush: zlib.constants.BROTLI_OPERATION_FLUSH,
|
|
||||||
finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
|
|
||||||
}
|
|
||||||
|
|
||||||
const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
|
|
||||||
|
|
||||||
const {http: httpFollow, https: httpsFollow} = followRedirects;
|
|
||||||
|
|
||||||
const isHttps = /https:?/;
|
|
||||||
|
|
||||||
const supportedProtocols = platform.protocols.map(protocol => {
|
|
||||||
return protocol + ':';
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If the proxy or config beforeRedirects functions are defined, call them with the options
|
|
||||||
* object.
|
|
||||||
*
|
|
||||||
* @param {Object<string, any>} options - The options object that was passed to the request.
|
|
||||||
*
|
|
||||||
* @returns {Object<string, any>}
|
|
||||||
*/
|
|
||||||
function dispatchBeforeRedirect(options, responseDetails) {
|
|
||||||
if (options.beforeRedirects.proxy) {
|
|
||||||
options.beforeRedirects.proxy(options);
|
|
||||||
}
|
|
||||||
if (options.beforeRedirects.config) {
|
|
||||||
options.beforeRedirects.config(options, responseDetails);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* If the proxy or config afterRedirects functions are defined, call them with the options
|
|
||||||
*
|
*
|
||||||
* @param {http.ClientRequestArgs} options
|
* @param {http.ClientRequestArgs} options
|
||||||
* @param {AxiosProxyConfig} configProxy configuration from Axios options object
|
* @param {AxiosProxyConfig} proxy
|
||||||
* @param {string} location
|
* @param {string} location
|
||||||
*
|
|
||||||
* @returns {http.ClientRequestArgs}
|
|
||||||
*/
|
*/
|
||||||
function setProxy(options, configProxy, location) {
|
function setProxy(options, proxy, location) {
|
||||||
let proxy = configProxy;
|
options.hostname = proxy.host;
|
||||||
if (!proxy && proxy !== false) {
|
options.host = proxy.host;
|
||||||
const proxyUrl = getProxyForUrl(location);
|
options.port = proxy.port;
|
||||||
if (proxyUrl) {
|
options.path = location;
|
||||||
proxy = new URL(proxyUrl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (proxy) {
|
|
||||||
// Basic proxy authorization
|
|
||||||
if (proxy.username) {
|
|
||||||
proxy.auth = (proxy.username || '') + ':' + (proxy.password || '');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (proxy.auth) {
|
// Basic proxy authorization
|
||||||
// Support proxy auth object form
|
if (proxy.auth) {
|
||||||
if (proxy.auth.username || proxy.auth.password) {
|
var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
|
||||||
proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
|
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
|
||||||
}
|
|
||||||
const base64 = Buffer
|
|
||||||
.from(proxy.auth, 'utf8')
|
|
||||||
.toString('base64');
|
|
||||||
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
|
|
||||||
}
|
|
||||||
|
|
||||||
options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
|
|
||||||
const proxyHost = proxy.hostname || proxy.host;
|
|
||||||
options.hostname = proxyHost;
|
|
||||||
// Replace 'host' since options is not a URL object
|
|
||||||
options.host = proxyHost;
|
|
||||||
options.port = proxy.port;
|
|
||||||
options.path = location;
|
|
||||||
if (proxy.protocol) {
|
|
||||||
options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
|
// If a proxy is used, any redirects must also pass through the proxy
|
||||||
// Configure proxy for redirected request, passing the original config proxy to apply
|
options.beforeRedirect = function beforeRedirect(redirection) {
|
||||||
// the exact same logic as if the redirected request was performed by axios directly.
|
redirection.headers.host = redirection.host;
|
||||||
setProxy(redirectOptions, configProxy, redirectOptions.href);
|
setProxy(redirection, proxy, redirection.href);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process';
|
|
||||||
|
|
||||||
// temporary hotfix
|
|
||||||
|
|
||||||
const wrapAsync = (asyncExecutor) => {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
let onDone;
|
|
||||||
let isDone;
|
|
||||||
|
|
||||||
const done = (value, isRejected) => {
|
|
||||||
if (isDone) return;
|
|
||||||
isDone = true;
|
|
||||||
onDone && onDone(value, isRejected);
|
|
||||||
}
|
|
||||||
|
|
||||||
const _resolve = (value) => {
|
|
||||||
done(value);
|
|
||||||
resolve(value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const _reject = (reason) => {
|
|
||||||
done(reason, true);
|
|
||||||
reject(reason);
|
|
||||||
}
|
|
||||||
|
|
||||||
asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
|
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
const resolveFamily = ({address, family}) => {
|
|
||||||
if (!utils.isString(address)) {
|
|
||||||
throw TypeError('address must be a string');
|
|
||||||
}
|
|
||||||
return ({
|
|
||||||
address,
|
|
||||||
family: family || (address.indexOf('.') < 0 ? 6 : 4)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : {address, family});
|
|
||||||
|
|
||||||
/*eslint consistent-return:0*/
|
/*eslint consistent-return:0*/
|
||||||
export default isHttpAdapterSupported && function httpAdapter(config) {
|
module.exports = function httpAdapter(config) {
|
||||||
return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
|
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
|
||||||
let {data, lookup, family} = config;
|
var resolve = function resolve(value) {
|
||||||
const {responseType, responseEncoding} = config;
|
resolvePromise(value);
|
||||||
const method = config.method.toUpperCase();
|
};
|
||||||
let isDone;
|
var reject = function reject(value) {
|
||||||
let rejected = false;
|
rejectPromise(value);
|
||||||
let req;
|
};
|
||||||
|
var data = config.data;
|
||||||
if (lookup) {
|
var headers = config.headers;
|
||||||
const _lookup = callbackify(lookup, (value) => utils.isArray(value) ? value : [value]);
|
|
||||||
// hotfix to support opt.all option which is required for node 20.x
|
|
||||||
lookup = (hostname, opt, cb) => {
|
|
||||||
_lookup(hostname, opt, (err, arg0, arg1) => {
|
|
||||||
if (err) {
|
|
||||||
return cb(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
const addresses = utils.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
|
|
||||||
|
|
||||||
opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// temporary internal emitter until the AxiosRequest class will be implemented
|
|
||||||
const emitter = new EventEmitter();
|
|
||||||
|
|
||||||
const onFinished = () => {
|
|
||||||
if (config.cancelToken) {
|
|
||||||
config.cancelToken.unsubscribe(abort);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (config.signal) {
|
|
||||||
config.signal.removeEventListener('abort', abort);
|
|
||||||
}
|
|
||||||
|
|
||||||
emitter.removeAllListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
onDone((value, isRejected) => {
|
|
||||||
isDone = true;
|
|
||||||
if (isRejected) {
|
|
||||||
rejected = true;
|
|
||||||
onFinished();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
function abort(reason) {
|
|
||||||
emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
|
|
||||||
}
|
|
||||||
|
|
||||||
emitter.once('abort', reject);
|
|
||||||
|
|
||||||
if (config.cancelToken || config.signal) {
|
|
||||||
config.cancelToken && config.cancelToken.subscribe(abort);
|
|
||||||
if (config.signal) {
|
|
||||||
config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse url
|
|
||||||
const fullPath = buildFullPath(config.baseURL, config.url);
|
|
||||||
const parsed = new URL(fullPath, 'http://localhost');
|
|
||||||
const protocol = parsed.protocol || supportedProtocols[0];
|
|
||||||
|
|
||||||
if (protocol === 'data:') {
|
|
||||||
let convertedData;
|
|
||||||
|
|
||||||
if (method !== 'GET') {
|
|
||||||
return settle(resolve, reject, {
|
|
||||||
status: 405,
|
|
||||||
statusText: 'method not allowed',
|
|
||||||
headers: {},
|
|
||||||
config
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
convertedData = fromDataURI(config.url, responseType === 'blob', {
|
|
||||||
Blob: config.env && config.env.Blob
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (responseType === 'text') {
|
|
||||||
convertedData = convertedData.toString(responseEncoding);
|
|
||||||
|
|
||||||
if (!responseEncoding || responseEncoding === 'utf8') {
|
|
||||||
convertedData = utils.stripBOM(convertedData);
|
|
||||||
}
|
|
||||||
} else if (responseType === 'stream') {
|
|
||||||
convertedData = stream.Readable.from(convertedData);
|
|
||||||
}
|
|
||||||
|
|
||||||
return settle(resolve, reject, {
|
|
||||||
data: convertedData,
|
|
||||||
status: 200,
|
|
||||||
statusText: 'OK',
|
|
||||||
headers: new AxiosHeaders(),
|
|
||||||
config
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (supportedProtocols.indexOf(protocol) === -1) {
|
|
||||||
return reject(new AxiosError(
|
|
||||||
'Unsupported protocol ' + protocol,
|
|
||||||
AxiosError.ERR_BAD_REQUEST,
|
|
||||||
config
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
const headers = AxiosHeaders.from(config.headers).normalize();
|
|
||||||
|
|
||||||
// Set User-Agent (required by some servers)
|
// Set User-Agent (required by some servers)
|
||||||
// See https://github.com/axios/axios/issues/69
|
// See https://github.com/axios/axios/issues/69
|
||||||
// User-Agent is specified; handle case where no UA header is desired
|
if ('User-Agent' in headers || 'user-agent' in headers) {
|
||||||
// Only set header if it hasn't been set in config
|
// User-Agent is specified; handle case where no UA header is desired
|
||||||
headers.set('User-Agent', 'axios/' + VERSION, false);
|
if (!headers['User-Agent'] && !headers['user-agent']) {
|
||||||
|
delete headers['User-Agent'];
|
||||||
const onDownloadProgress = config.onDownloadProgress;
|
delete headers['user-agent'];
|
||||||
const onUploadProgress = config.onUploadProgress;
|
|
||||||
const maxRate = config.maxRate;
|
|
||||||
let maxUploadRate = undefined;
|
|
||||||
let maxDownloadRate = undefined;
|
|
||||||
|
|
||||||
// support for spec compliant FormData objects
|
|
||||||
if (utils.isSpecCompliantForm(data)) {
|
|
||||||
const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
|
|
||||||
|
|
||||||
data = formDataToStream(data, (formHeaders) => {
|
|
||||||
headers.set(formHeaders);
|
|
||||||
}, {
|
|
||||||
tag: `axios-${VERSION}-boundary`,
|
|
||||||
boundary: userBoundary && userBoundary[1] || undefined
|
|
||||||
});
|
|
||||||
// support for https://www.npmjs.com/package/form-data api
|
|
||||||
} else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
|
|
||||||
headers.set(data.getHeaders());
|
|
||||||
|
|
||||||
if (!headers.hasContentLength()) {
|
|
||||||
try {
|
|
||||||
const knownLength = await util.promisify(data.getLength).call(data);
|
|
||||||
Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
|
|
||||||
/*eslint no-empty:0*/
|
|
||||||
} catch (e) {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else if (utils.isBlob(data)) {
|
// Otherwise, use specified value
|
||||||
data.size && headers.setContentType(data.type || 'application/octet-stream');
|
} else {
|
||||||
headers.setContentLength(data.size || 0);
|
// Only set header if it hasn't been set in config
|
||||||
data = stream.Readable.from(readBlob(data));
|
headers['User-Agent'] = 'axios/' + pkg.version;
|
||||||
} else if (data && !utils.isStream(data)) {
|
}
|
||||||
|
|
||||||
|
if (data && !utils.isStream(data)) {
|
||||||
if (Buffer.isBuffer(data)) {
|
if (Buffer.isBuffer(data)) {
|
||||||
// Nothing to do...
|
// Nothing to do...
|
||||||
} else if (utils.isArrayBuffer(data)) {
|
} else if (utils.isArrayBuffer(data)) {
|
||||||
|
@ -318,314 +75,218 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
|
||||||
} else if (utils.isString(data)) {
|
} else if (utils.isString(data)) {
|
||||||
data = Buffer.from(data, 'utf-8');
|
data = Buffer.from(data, 'utf-8');
|
||||||
} else {
|
} else {
|
||||||
return reject(new AxiosError(
|
return reject(createError(
|
||||||
'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
|
'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
|
||||||
AxiosError.ERR_BAD_REQUEST,
|
|
||||||
config
|
config
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add Content-Length header if data exists
|
// Add Content-Length header if data exists
|
||||||
headers.setContentLength(data.length, false);
|
headers['Content-Length'] = data.length;
|
||||||
|
|
||||||
if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
|
|
||||||
return reject(new AxiosError(
|
|
||||||
'Request body larger than maxBodyLength limit',
|
|
||||||
AxiosError.ERR_BAD_REQUEST,
|
|
||||||
config
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const contentLength = utils.toFiniteNumber(headers.getContentLength());
|
|
||||||
|
|
||||||
if (utils.isArray(maxRate)) {
|
|
||||||
maxUploadRate = maxRate[0];
|
|
||||||
maxDownloadRate = maxRate[1];
|
|
||||||
} else {
|
|
||||||
maxUploadRate = maxDownloadRate = maxRate;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data && (onUploadProgress || maxUploadRate)) {
|
|
||||||
if (!utils.isStream(data)) {
|
|
||||||
data = stream.Readable.from(data, {objectMode: false});
|
|
||||||
}
|
|
||||||
|
|
||||||
data = stream.pipeline([data, new AxiosTransformStream({
|
|
||||||
length: contentLength,
|
|
||||||
maxRate: utils.toFiniteNumber(maxUploadRate)
|
|
||||||
})], utils.noop);
|
|
||||||
|
|
||||||
onUploadProgress && data.on('progress', progress => {
|
|
||||||
onUploadProgress(Object.assign(progress, {
|
|
||||||
upload: true
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// HTTP basic authentication
|
// HTTP basic authentication
|
||||||
let auth = undefined;
|
var auth = undefined;
|
||||||
if (config.auth) {
|
if (config.auth) {
|
||||||
const username = config.auth.username || '';
|
var username = config.auth.username || '';
|
||||||
const password = config.auth.password || '';
|
var password = config.auth.password || '';
|
||||||
auth = username + ':' + password;
|
auth = username + ':' + password;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!auth && parsed.username) {
|
// Parse url
|
||||||
const urlUsername = parsed.username;
|
var fullPath = buildFullPath(config.baseURL, config.url);
|
||||||
const urlPassword = parsed.password;
|
var parsed = url.parse(fullPath);
|
||||||
|
var protocol = parsed.protocol || 'http:';
|
||||||
|
|
||||||
|
if (!auth && parsed.auth) {
|
||||||
|
var urlAuth = parsed.auth.split(':');
|
||||||
|
var urlUsername = urlAuth[0] || '';
|
||||||
|
var urlPassword = urlAuth[1] || '';
|
||||||
auth = urlUsername + ':' + urlPassword;
|
auth = urlUsername + ':' + urlPassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
auth && headers.delete('authorization');
|
if (auth) {
|
||||||
|
delete headers.Authorization;
|
||||||
let path;
|
|
||||||
|
|
||||||
try {
|
|
||||||
path = buildURL(
|
|
||||||
parsed.pathname + parsed.search,
|
|
||||||
config.params,
|
|
||||||
config.paramsSerializer
|
|
||||||
).replace(/^\?/, '');
|
|
||||||
} catch (err) {
|
|
||||||
const customErr = new Error(err.message);
|
|
||||||
customErr.config = config;
|
|
||||||
customErr.url = config.url;
|
|
||||||
customErr.exists = true;
|
|
||||||
return reject(customErr);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
headers.set(
|
var isHttpsRequest = isHttps.test(protocol);
|
||||||
'Accept-Encoding',
|
var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
|
||||||
'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false
|
|
||||||
);
|
|
||||||
|
|
||||||
const options = {
|
var options = {
|
||||||
path,
|
path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
|
||||||
method: method,
|
method: config.method.toUpperCase(),
|
||||||
headers: headers.toJSON(),
|
headers: headers,
|
||||||
|
agent: agent,
|
||||||
agents: { http: config.httpAgent, https: config.httpsAgent },
|
agents: { http: config.httpAgent, https: config.httpsAgent },
|
||||||
auth,
|
auth: auth
|
||||||
protocol,
|
|
||||||
family,
|
|
||||||
beforeRedirect: dispatchBeforeRedirect,
|
|
||||||
beforeRedirects: {}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// cacheable-lookup integration hotfix
|
|
||||||
!utils.isUndefined(lookup) && (options.lookup = lookup);
|
|
||||||
|
|
||||||
if (config.socketPath) {
|
if (config.socketPath) {
|
||||||
options.socketPath = config.socketPath;
|
options.socketPath = config.socketPath;
|
||||||
} else {
|
} else {
|
||||||
options.hostname = parsed.hostname;
|
options.hostname = parsed.hostname;
|
||||||
options.port = parsed.port;
|
options.port = parsed.port;
|
||||||
setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let transport;
|
var proxy = config.proxy;
|
||||||
const isHttpsRequest = isHttps.test(options.protocol);
|
if (!proxy && proxy !== false) {
|
||||||
options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
|
var proxyEnv = protocol.slice(0, -1) + '_proxy';
|
||||||
|
var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
|
||||||
|
if (proxyUrl) {
|
||||||
|
var parsedProxyUrl = url.parse(proxyUrl);
|
||||||
|
var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY;
|
||||||
|
var shouldProxy = true;
|
||||||
|
|
||||||
|
if (noProxyEnv) {
|
||||||
|
var noProxy = noProxyEnv.split(',').map(function trim(s) {
|
||||||
|
return s.trim();
|
||||||
|
});
|
||||||
|
|
||||||
|
shouldProxy = !noProxy.some(function proxyMatch(proxyElement) {
|
||||||
|
if (!proxyElement) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (proxyElement === '*') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (proxyElement[0] === '.' &&
|
||||||
|
parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed.hostname === proxyElement;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldProxy) {
|
||||||
|
proxy = {
|
||||||
|
host: parsedProxyUrl.hostname,
|
||||||
|
port: parsedProxyUrl.port,
|
||||||
|
protocol: parsedProxyUrl.protocol
|
||||||
|
};
|
||||||
|
|
||||||
|
if (parsedProxyUrl.auth) {
|
||||||
|
var proxyUrlAuth = parsedProxyUrl.auth.split(':');
|
||||||
|
proxy.auth = {
|
||||||
|
username: proxyUrlAuth[0],
|
||||||
|
password: proxyUrlAuth[1]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (proxy) {
|
||||||
|
options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
|
||||||
|
setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
var transport;
|
||||||
|
var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
|
||||||
if (config.transport) {
|
if (config.transport) {
|
||||||
transport = config.transport;
|
transport = config.transport;
|
||||||
} else if (config.maxRedirects === 0) {
|
} else if (config.maxRedirects === 0) {
|
||||||
transport = isHttpsRequest ? https : http;
|
transport = isHttpsProxy ? https : http;
|
||||||
} else {
|
} else {
|
||||||
if (config.maxRedirects) {
|
if (config.maxRedirects) {
|
||||||
options.maxRedirects = config.maxRedirects;
|
options.maxRedirects = config.maxRedirects;
|
||||||
}
|
}
|
||||||
if (config.beforeRedirect) {
|
transport = isHttpsProxy ? httpsFollow : httpFollow;
|
||||||
options.beforeRedirects.config = config.beforeRedirect;
|
|
||||||
}
|
|
||||||
transport = isHttpsRequest ? httpsFollow : httpFollow;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.maxBodyLength > -1) {
|
if (config.maxBodyLength > -1) {
|
||||||
options.maxBodyLength = config.maxBodyLength;
|
options.maxBodyLength = config.maxBodyLength;
|
||||||
} else {
|
|
||||||
// follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
|
|
||||||
options.maxBodyLength = Infinity;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (config.insecureHTTPParser) {
|
|
||||||
options.insecureHTTPParser = config.insecureHTTPParser;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create the request
|
// Create the request
|
||||||
req = transport.request(options, function handleResponse(res) {
|
var req = transport.request(options, function handleResponse(res) {
|
||||||
if (req.destroyed) return;
|
if (req.aborted) return;
|
||||||
|
|
||||||
const streams = [res];
|
// uncompress the response body transparently if required
|
||||||
|
var stream = res;
|
||||||
const responseLength = +res.headers['content-length'];
|
|
||||||
|
|
||||||
if (onDownloadProgress) {
|
|
||||||
const transformStream = new AxiosTransformStream({
|
|
||||||
length: utils.toFiniteNumber(responseLength),
|
|
||||||
maxRate: utils.toFiniteNumber(maxDownloadRate)
|
|
||||||
});
|
|
||||||
|
|
||||||
onDownloadProgress && transformStream.on('progress', progress => {
|
|
||||||
onDownloadProgress(Object.assign(progress, {
|
|
||||||
download: true
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
|
|
||||||
streams.push(transformStream);
|
|
||||||
}
|
|
||||||
|
|
||||||
// decompress the response body transparently if required
|
|
||||||
let responseStream = res;
|
|
||||||
|
|
||||||
// return the last request in case of redirects
|
// return the last request in case of redirects
|
||||||
const lastRequest = res.req || req;
|
var lastRequest = res.req || req;
|
||||||
|
|
||||||
// if decompress disabled we should not decompress
|
|
||||||
if (config.decompress !== false && res.headers['content-encoding']) {
|
|
||||||
// if no content, but headers still say that it is encoded,
|
|
||||||
// remove the header not confuse downstream operations
|
|
||||||
if (method === 'HEAD' || res.statusCode === 204) {
|
|
||||||
delete res.headers['content-encoding'];
|
|
||||||
}
|
|
||||||
|
|
||||||
switch ((res.headers['content-encoding'] || '').toLowerCase()) {
|
// if no content, is HEAD request or decompress disabled we should not decompress
|
||||||
|
if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) {
|
||||||
|
switch (res.headers['content-encoding']) {
|
||||||
/*eslint default-case:0*/
|
/*eslint default-case:0*/
|
||||||
case 'gzip':
|
case 'gzip':
|
||||||
case 'x-gzip':
|
|
||||||
case 'compress':
|
case 'compress':
|
||||||
case 'x-compress':
|
|
||||||
// add the unzipper to the body stream processing pipeline
|
|
||||||
streams.push(zlib.createUnzip(zlibOptions));
|
|
||||||
|
|
||||||
// remove the content-encoding in order to not confuse downstream operations
|
|
||||||
delete res.headers['content-encoding'];
|
|
||||||
break;
|
|
||||||
case 'deflate':
|
case 'deflate':
|
||||||
streams.push(new ZlibHeaderTransformStream());
|
// add the unzipper to the body stream processing pipeline
|
||||||
|
stream = stream.pipe(zlib.createUnzip());
|
||||||
// add the unzipper to the body stream processing pipeline
|
|
||||||
streams.push(zlib.createUnzip(zlibOptions));
|
|
||||||
|
|
||||||
// remove the content-encoding in order to not confuse downstream operations
|
// remove the content-encoding in order to not confuse downstream operations
|
||||||
delete res.headers['content-encoding'];
|
delete res.headers['content-encoding'];
|
||||||
break;
|
break;
|
||||||
case 'br':
|
|
||||||
if (isBrotliSupported) {
|
|
||||||
streams.push(zlib.createBrotliDecompress(brotliOptions));
|
|
||||||
delete res.headers['content-encoding'];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
|
var response = {
|
||||||
|
|
||||||
const offListeners = stream.finished(responseStream, () => {
|
|
||||||
offListeners();
|
|
||||||
onFinished();
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = {
|
|
||||||
status: res.statusCode,
|
status: res.statusCode,
|
||||||
statusText: res.statusMessage,
|
statusText: res.statusMessage,
|
||||||
headers: new AxiosHeaders(res.headers),
|
headers: res.headers,
|
||||||
config,
|
config: config,
|
||||||
request: lastRequest
|
request: lastRequest
|
||||||
};
|
};
|
||||||
|
|
||||||
if (responseType === 'stream') {
|
if (config.responseType === 'stream') {
|
||||||
response.data = responseStream;
|
response.data = stream;
|
||||||
settle(resolve, reject, response);
|
settle(resolve, reject, response);
|
||||||
} else {
|
} else {
|
||||||
const responseBuffer = [];
|
var responseBuffer = [];
|
||||||
let totalResponseBytes = 0;
|
var totalResponseBytes = 0;
|
||||||
|
stream.on('data', function handleStreamData(chunk) {
|
||||||
responseStream.on('data', function handleStreamData(chunk) {
|
|
||||||
responseBuffer.push(chunk);
|
responseBuffer.push(chunk);
|
||||||
totalResponseBytes += chunk.length;
|
totalResponseBytes += chunk.length;
|
||||||
|
|
||||||
// make sure the content length is not over the maxContentLength if specified
|
// make sure the content length is not over the maxContentLength if specified
|
||||||
if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
|
if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
|
||||||
// stream.destroy() emit aborted event before calling reject() on Node.js v16
|
stream.destroy();
|
||||||
rejected = true;
|
reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
|
||||||
responseStream.destroy();
|
config, null, lastRequest));
|
||||||
reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
|
|
||||||
AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
responseStream.on('aborted', function handlerStreamAborted() {
|
stream.on('error', function handleStreamError(err) {
|
||||||
if (rejected) {
|
if (req.aborted) return;
|
||||||
return;
|
reject(enhanceError(err, config, null, lastRequest));
|
||||||
}
|
|
||||||
|
|
||||||
const err = new AxiosError(
|
|
||||||
'maxContentLength size of ' + config.maxContentLength + ' exceeded',
|
|
||||||
AxiosError.ERR_BAD_RESPONSE,
|
|
||||||
config,
|
|
||||||
lastRequest
|
|
||||||
);
|
|
||||||
responseStream.destroy(err);
|
|
||||||
reject(err);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
responseStream.on('error', function handleStreamError(err) {
|
stream.on('end', function handleStreamEnd() {
|
||||||
if (req.destroyed) return;
|
var responseData = Buffer.concat(responseBuffer);
|
||||||
reject(AxiosError.from(err, null, config, lastRequest));
|
if (config.responseType !== 'arraybuffer') {
|
||||||
});
|
responseData = responseData.toString(config.responseEncoding);
|
||||||
|
if (!config.responseEncoding || config.responseEncoding === 'utf8') {
|
||||||
responseStream.on('end', function handleStreamEnd() {
|
responseData = utils.stripBOM(responseData);
|
||||||
try {
|
|
||||||
let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
|
|
||||||
if (responseType !== 'arraybuffer') {
|
|
||||||
responseData = responseData.toString(responseEncoding);
|
|
||||||
if (!responseEncoding || responseEncoding === 'utf8') {
|
|
||||||
responseData = utils.stripBOM(responseData);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
response.data = responseData;
|
|
||||||
} catch (err) {
|
|
||||||
return reject(AxiosError.from(err, null, config, response.request, response));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
response.data = responseData;
|
||||||
settle(resolve, reject, response);
|
settle(resolve, reject, response);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
emitter.once('abort', err => {
|
|
||||||
if (!responseStream.destroyed) {
|
|
||||||
responseStream.emit('error', err);
|
|
||||||
responseStream.destroy();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
emitter.once('abort', err => {
|
|
||||||
reject(err);
|
|
||||||
req.destroy(err);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle errors
|
// Handle errors
|
||||||
req.on('error', function handleRequestError(err) {
|
req.on('error', function handleRequestError(err) {
|
||||||
// @todo remove
|
if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return;
|
||||||
// if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
|
reject(enhanceError(err, config, null, req));
|
||||||
reject(AxiosError.from(err, null, config, req));
|
|
||||||
});
|
|
||||||
|
|
||||||
// set tcp keep alive to prevent drop connection by peer
|
|
||||||
req.on('socket', function handleRequestSocket(socket) {
|
|
||||||
// default interval of sending ack packet is 1 minute
|
|
||||||
socket.setKeepAlive(true, 1000 * 60);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle request timeout
|
// Handle request timeout
|
||||||
if (config.timeout) {
|
if (config.timeout) {
|
||||||
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
|
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
|
||||||
const timeout = parseInt(config.timeout, 10);
|
var timeout = parseInt(config.timeout, 10);
|
||||||
|
|
||||||
if (Number.isNaN(timeout)) {
|
if (isNaN(timeout)) {
|
||||||
reject(new AxiosError(
|
reject(createError(
|
||||||
'error trying to parse `config.timeout` to int',
|
'error trying to parse `config.timeout` to int',
|
||||||
AxiosError.ERR_BAD_OPTION_VALUE,
|
|
||||||
config,
|
config,
|
||||||
|
'ERR_PARSE_TIMEOUT',
|
||||||
req
|
req
|
||||||
));
|
));
|
||||||
|
|
||||||
|
@ -635,51 +296,36 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
|
||||||
// Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
|
// Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
|
||||||
// And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
|
// And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
|
||||||
// At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
|
// At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
|
||||||
// And then these socket which be hang up will devouring CPU little by little.
|
// And then these socket which be hang up will devoring CPU little by little.
|
||||||
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
|
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
|
||||||
req.setTimeout(timeout, function handleRequestTimeout() {
|
req.setTimeout(timeout, function handleRequestTimeout() {
|
||||||
if (isDone) return;
|
req.abort();
|
||||||
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
|
reject(createError(
|
||||||
const transitional = config.transitional || transitionalDefaults;
|
'timeout of ' + timeout + 'ms exceeded',
|
||||||
if (config.timeoutErrorMessage) {
|
|
||||||
timeoutErrorMessage = config.timeoutErrorMessage;
|
|
||||||
}
|
|
||||||
reject(new AxiosError(
|
|
||||||
timeoutErrorMessage,
|
|
||||||
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
|
|
||||||
config,
|
config,
|
||||||
|
config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
|
||||||
req
|
req
|
||||||
));
|
));
|
||||||
abort();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (config.cancelToken) {
|
||||||
|
// Handle cancellation
|
||||||
|
config.cancelToken.promise.then(function onCanceled(cancel) {
|
||||||
|
if (req.aborted) return;
|
||||||
|
|
||||||
|
req.abort();
|
||||||
|
reject(cancel);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Send the request
|
// Send the request
|
||||||
if (utils.isStream(data)) {
|
if (utils.isStream(data)) {
|
||||||
let ended = false;
|
data.on('error', function handleStreamError(err) {
|
||||||
let errored = false;
|
reject(enhanceError(err, config, null, req));
|
||||||
|
}).pipe(req);
|
||||||
data.on('end', () => {
|
|
||||||
ended = true;
|
|
||||||
});
|
|
||||||
|
|
||||||
data.once('error', err => {
|
|
||||||
errored = true;
|
|
||||||
req.destroy(err);
|
|
||||||
});
|
|
||||||
|
|
||||||
data.on('close', () => {
|
|
||||||
if (!ended && !errored) {
|
|
||||||
abort(new CanceledError('Request stream has been aborted', config, req));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
data.pipe(req);
|
|
||||||
} else {
|
} else {
|
||||||
req.end(data);
|
req.end(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
export const __setProxy = setProxy;
|
|
||||||
|
|
|
@ -1,89 +1,34 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import utils from './../utils.js';
|
var utils = require('./../utils');
|
||||||
import settle from './../core/settle.js';
|
var settle = require('./../core/settle');
|
||||||
import cookies from './../helpers/cookies.js';
|
var cookies = require('./../helpers/cookies');
|
||||||
import buildURL from './../helpers/buildURL.js';
|
var buildURL = require('./../helpers/buildURL');
|
||||||
import buildFullPath from '../core/buildFullPath.js';
|
var buildFullPath = require('../core/buildFullPath');
|
||||||
import isURLSameOrigin from './../helpers/isURLSameOrigin.js';
|
var parseHeaders = require('./../helpers/parseHeaders');
|
||||||
import transitionalDefaults from '../defaults/transitional.js';
|
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
|
||||||
import AxiosError from '../core/AxiosError.js';
|
var createError = require('../core/createError');
|
||||||
import CanceledError from '../cancel/CanceledError.js';
|
|
||||||
import parseProtocol from '../helpers/parseProtocol.js';
|
|
||||||
import platform from '../platform/index.js';
|
|
||||||
import AxiosHeaders from '../core/AxiosHeaders.js';
|
|
||||||
import speedometer from '../helpers/speedometer.js';
|
|
||||||
|
|
||||||
function progressEventReducer(listener, isDownloadStream) {
|
module.exports = function xhrAdapter(config) {
|
||||||
let bytesNotified = 0;
|
|
||||||
const _speedometer = speedometer(50, 250);
|
|
||||||
|
|
||||||
return e => {
|
|
||||||
const loaded = e.loaded;
|
|
||||||
const total = e.lengthComputable ? e.total : undefined;
|
|
||||||
const progressBytes = loaded - bytesNotified;
|
|
||||||
const rate = _speedometer(progressBytes);
|
|
||||||
const inRange = loaded <= total;
|
|
||||||
|
|
||||||
bytesNotified = loaded;
|
|
||||||
|
|
||||||
const data = {
|
|
||||||
loaded,
|
|
||||||
total,
|
|
||||||
progress: total ? (loaded / total) : undefined,
|
|
||||||
bytes: progressBytes,
|
|
||||||
rate: rate ? rate : undefined,
|
|
||||||
estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
|
|
||||||
event: e
|
|
||||||
};
|
|
||||||
|
|
||||||
data[isDownloadStream ? 'download' : 'upload'] = true;
|
|
||||||
|
|
||||||
listener(data);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
|
|
||||||
|
|
||||||
export default isXHRAdapterSupported && function (config) {
|
|
||||||
return new Promise(function dispatchXhrRequest(resolve, reject) {
|
return new Promise(function dispatchXhrRequest(resolve, reject) {
|
||||||
let requestData = config.data;
|
var requestData = config.data;
|
||||||
const requestHeaders = AxiosHeaders.from(config.headers).normalize();
|
var requestHeaders = config.headers;
|
||||||
let {responseType, withXSRFToken} = config;
|
var responseType = config.responseType;
|
||||||
let onCanceled;
|
|
||||||
function done() {
|
|
||||||
if (config.cancelToken) {
|
|
||||||
config.cancelToken.unsubscribe(onCanceled);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (config.signal) {
|
|
||||||
config.signal.removeEventListener('abort', onCanceled);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let contentType;
|
|
||||||
|
|
||||||
if (utils.isFormData(requestData)) {
|
if (utils.isFormData(requestData)) {
|
||||||
if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
|
delete requestHeaders['Content-Type']; // Let the browser set it
|
||||||
requestHeaders.setContentType(false); // Let the browser set it
|
|
||||||
} else if ((contentType = requestHeaders.getContentType()) !== false) {
|
|
||||||
// fix semicolon duplication issue for ReactNative FormData implementation
|
|
||||||
const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
|
|
||||||
requestHeaders.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let request = new XMLHttpRequest();
|
var request = new XMLHttpRequest();
|
||||||
|
|
||||||
// HTTP basic authentication
|
// HTTP basic authentication
|
||||||
if (config.auth) {
|
if (config.auth) {
|
||||||
const username = config.auth.username || '';
|
var username = config.auth.username || '';
|
||||||
const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
|
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
|
||||||
requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
|
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
|
||||||
}
|
}
|
||||||
|
|
||||||
const fullPath = buildFullPath(config.baseURL, config.url);
|
var fullPath = buildFullPath(config.baseURL, config.url);
|
||||||
|
|
||||||
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
|
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
|
||||||
|
|
||||||
// Set the request timeout in MS
|
// Set the request timeout in MS
|
||||||
|
@ -94,27 +39,19 @@ export default isXHRAdapterSupported && function (config) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Prepare the response
|
// Prepare the response
|
||||||
const responseHeaders = AxiosHeaders.from(
|
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
|
||||||
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
|
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
|
||||||
);
|
|
||||||
const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
|
|
||||||
request.responseText : request.response;
|
request.responseText : request.response;
|
||||||
const response = {
|
var response = {
|
||||||
data: responseData,
|
data: responseData,
|
||||||
status: request.status,
|
status: request.status,
|
||||||
statusText: request.statusText,
|
statusText: request.statusText,
|
||||||
headers: responseHeaders,
|
headers: responseHeaders,
|
||||||
config,
|
config: config,
|
||||||
request
|
request: request
|
||||||
};
|
};
|
||||||
|
|
||||||
settle(function _resolve(value) {
|
settle(resolve, reject, response);
|
||||||
resolve(value);
|
|
||||||
done();
|
|
||||||
}, function _reject(err) {
|
|
||||||
reject(err);
|
|
||||||
done();
|
|
||||||
}, response);
|
|
||||||
|
|
||||||
// Clean up request
|
// Clean up request
|
||||||
request = null;
|
request = null;
|
||||||
|
@ -149,7 +86,7 @@ export default isXHRAdapterSupported && function (config) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
|
reject(createError('Request aborted', config, 'ECONNABORTED', request));
|
||||||
|
|
||||||
// Clean up request
|
// Clean up request
|
||||||
request = null;
|
request = null;
|
||||||
|
@ -159,7 +96,7 @@ export default isXHRAdapterSupported && function (config) {
|
||||||
request.onerror = function handleError() {
|
request.onerror = function handleError() {
|
||||||
// Real errors are hidden from us by the browser
|
// Real errors are hidden from us by the browser
|
||||||
// onerror should only fire if it's a network error
|
// onerror should only fire if it's a network error
|
||||||
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
|
reject(createError('Network Error', config, null, request));
|
||||||
|
|
||||||
// Clean up request
|
// Clean up request
|
||||||
request = null;
|
request = null;
|
||||||
|
@ -167,15 +104,14 @@ export default isXHRAdapterSupported && function (config) {
|
||||||
|
|
||||||
// Handle timeout
|
// Handle timeout
|
||||||
request.ontimeout = function handleTimeout() {
|
request.ontimeout = function handleTimeout() {
|
||||||
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
|
var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
|
||||||
const transitional = config.transitional || transitionalDefaults;
|
|
||||||
if (config.timeoutErrorMessage) {
|
if (config.timeoutErrorMessage) {
|
||||||
timeoutErrorMessage = config.timeoutErrorMessage;
|
timeoutErrorMessage = config.timeoutErrorMessage;
|
||||||
}
|
}
|
||||||
reject(new AxiosError(
|
reject(createError(
|
||||||
timeoutErrorMessage,
|
timeoutErrorMessage,
|
||||||
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
|
|
||||||
config,
|
config,
|
||||||
|
config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
|
||||||
request));
|
request));
|
||||||
|
|
||||||
// Clean up request
|
// Clean up request
|
||||||
|
@ -185,26 +121,27 @@ export default isXHRAdapterSupported && function (config) {
|
||||||
// Add xsrf header
|
// Add xsrf header
|
||||||
// This is only done if running in a standard browser environment.
|
// This is only done if running in a standard browser environment.
|
||||||
// Specifically not if we're in a web worker, or react-native.
|
// Specifically not if we're in a web worker, or react-native.
|
||||||
if(platform.hasStandardBrowserEnv) {
|
if (utils.isStandardBrowserEnv()) {
|
||||||
withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config));
|
// Add xsrf header
|
||||||
|
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
|
||||||
|
cookies.read(config.xsrfCookieName) :
|
||||||
|
undefined;
|
||||||
|
|
||||||
if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(fullPath))) {
|
if (xsrfValue) {
|
||||||
// Add xsrf header
|
requestHeaders[config.xsrfHeaderName] = xsrfValue;
|
||||||
const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName);
|
|
||||||
|
|
||||||
if (xsrfValue) {
|
|
||||||
requestHeaders.set(config.xsrfHeaderName, xsrfValue);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove Content-Type if data is undefined
|
|
||||||
requestData === undefined && requestHeaders.setContentType(null);
|
|
||||||
|
|
||||||
// Add headers to the request
|
// Add headers to the request
|
||||||
if ('setRequestHeader' in request) {
|
if ('setRequestHeader' in request) {
|
||||||
utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
|
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
|
||||||
request.setRequestHeader(key, val);
|
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
|
||||||
|
// Remove Content-Type if data is undefined
|
||||||
|
delete requestHeaders[key];
|
||||||
|
} else {
|
||||||
|
// Otherwise add header to the request
|
||||||
|
request.setRequestHeader(key, val);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -220,41 +157,33 @@ export default isXHRAdapterSupported && function (config) {
|
||||||
|
|
||||||
// Handle progress if needed
|
// Handle progress if needed
|
||||||
if (typeof config.onDownloadProgress === 'function') {
|
if (typeof config.onDownloadProgress === 'function') {
|
||||||
request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
|
request.addEventListener('progress', config.onDownloadProgress);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Not all browsers support upload events
|
// Not all browsers support upload events
|
||||||
if (typeof config.onUploadProgress === 'function' && request.upload) {
|
if (typeof config.onUploadProgress === 'function' && request.upload) {
|
||||||
request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
|
request.upload.addEventListener('progress', config.onUploadProgress);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.cancelToken || config.signal) {
|
if (config.cancelToken) {
|
||||||
// Handle cancellation
|
// Handle cancellation
|
||||||
// eslint-disable-next-line func-names
|
config.cancelToken.promise.then(function onCanceled(cancel) {
|
||||||
onCanceled = cancel => {
|
|
||||||
if (!request) {
|
if (!request) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
|
|
||||||
request.abort();
|
request.abort();
|
||||||
|
reject(cancel);
|
||||||
|
// Clean up request
|
||||||
request = null;
|
request = null;
|
||||||
};
|
});
|
||||||
|
|
||||||
config.cancelToken && config.cancelToken.subscribe(onCanceled);
|
|
||||||
if (config.signal) {
|
|
||||||
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const protocol = parseProtocol(fullPath);
|
if (!requestData) {
|
||||||
|
requestData = null;
|
||||||
if (protocol && platform.protocols.indexOf(protocol) === -1) {
|
|
||||||
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Send the request
|
// Send the request
|
||||||
request.send(requestData || null);
|
request.send(requestData);
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,89 +1,56 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import utils from './utils.js';
|
var utils = require('./utils');
|
||||||
import bind from './helpers/bind.js';
|
var bind = require('./helpers/bind');
|
||||||
import Axios from './core/Axios.js';
|
var Axios = require('./core/Axios');
|
||||||
import mergeConfig from './core/mergeConfig.js';
|
var mergeConfig = require('./core/mergeConfig');
|
||||||
import defaults from './defaults/index.js';
|
var defaults = require('./defaults');
|
||||||
import formDataToJSON from './helpers/formDataToJSON.js';
|
|
||||||
import CanceledError from './cancel/CanceledError.js';
|
|
||||||
import CancelToken from './cancel/CancelToken.js';
|
|
||||||
import isCancel from './cancel/isCancel.js';
|
|
||||||
import {VERSION} from './env/data.js';
|
|
||||||
import toFormData from './helpers/toFormData.js';
|
|
||||||
import AxiosError from './core/AxiosError.js';
|
|
||||||
import spread from './helpers/spread.js';
|
|
||||||
import isAxiosError from './helpers/isAxiosError.js';
|
|
||||||
import AxiosHeaders from "./core/AxiosHeaders.js";
|
|
||||||
import adapters from './adapters/adapters.js';
|
|
||||||
import HttpStatusCode from './helpers/HttpStatusCode.js';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create an instance of Axios
|
* Create an instance of Axios
|
||||||
*
|
*
|
||||||
* @param {Object} defaultConfig The default config for the instance
|
* @param {Object} defaultConfig The default config for the instance
|
||||||
*
|
* @return {Axios} A new instance of Axios
|
||||||
* @returns {Axios} A new instance of Axios
|
|
||||||
*/
|
*/
|
||||||
function createInstance(defaultConfig) {
|
function createInstance(defaultConfig) {
|
||||||
const context = new Axios(defaultConfig);
|
var context = new Axios(defaultConfig);
|
||||||
const instance = bind(Axios.prototype.request, context);
|
var instance = bind(Axios.prototype.request, context);
|
||||||
|
|
||||||
// Copy axios.prototype to instance
|
// Copy axios.prototype to instance
|
||||||
utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});
|
utils.extend(instance, Axios.prototype, context);
|
||||||
|
|
||||||
// Copy context to instance
|
// Copy context to instance
|
||||||
utils.extend(instance, context, null, {allOwnKeys: true});
|
utils.extend(instance, context);
|
||||||
|
|
||||||
// Factory for creating new instances
|
|
||||||
instance.create = function create(instanceConfig) {
|
|
||||||
return createInstance(mergeConfig(defaultConfig, instanceConfig));
|
|
||||||
};
|
|
||||||
|
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create the default instance to be exported
|
// Create the default instance to be exported
|
||||||
const axios = createInstance(defaults);
|
var axios = createInstance(defaults);
|
||||||
|
|
||||||
// Expose Axios class to allow class inheritance
|
// Expose Axios class to allow class inheritance
|
||||||
axios.Axios = Axios;
|
axios.Axios = Axios;
|
||||||
|
|
||||||
|
// Factory for creating new instances
|
||||||
|
axios.create = function create(instanceConfig) {
|
||||||
|
return createInstance(mergeConfig(axios.defaults, instanceConfig));
|
||||||
|
};
|
||||||
|
|
||||||
// Expose Cancel & CancelToken
|
// Expose Cancel & CancelToken
|
||||||
axios.CanceledError = CanceledError;
|
axios.Cancel = require('./cancel/Cancel');
|
||||||
axios.CancelToken = CancelToken;
|
axios.CancelToken = require('./cancel/CancelToken');
|
||||||
axios.isCancel = isCancel;
|
axios.isCancel = require('./cancel/isCancel');
|
||||||
axios.VERSION = VERSION;
|
|
||||||
axios.toFormData = toFormData;
|
|
||||||
|
|
||||||
// Expose AxiosError class
|
|
||||||
axios.AxiosError = AxiosError;
|
|
||||||
|
|
||||||
// alias for CanceledError for backward compatibility
|
|
||||||
axios.Cancel = axios.CanceledError;
|
|
||||||
|
|
||||||
// Expose all/spread
|
// Expose all/spread
|
||||||
axios.all = function all(promises) {
|
axios.all = function all(promises) {
|
||||||
return Promise.all(promises);
|
return Promise.all(promises);
|
||||||
};
|
};
|
||||||
|
axios.spread = require('./helpers/spread');
|
||||||
axios.spread = spread;
|
|
||||||
|
|
||||||
// Expose isAxiosError
|
// Expose isAxiosError
|
||||||
axios.isAxiosError = isAxiosError;
|
axios.isAxiosError = require('./helpers/isAxiosError');
|
||||||
|
|
||||||
// Expose mergeConfig
|
module.exports = axios;
|
||||||
axios.mergeConfig = mergeConfig;
|
|
||||||
|
|
||||||
axios.AxiosHeaders = AxiosHeaders;
|
// Allow use of default import syntax in TypeScript
|
||||||
|
module.exports.default = axios;
|
||||||
axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
|
|
||||||
|
|
||||||
axios.getAdapter = adapters.getAdapter;
|
|
||||||
|
|
||||||
axios.HttpStatusCode = HttpStatusCode;
|
|
||||||
|
|
||||||
axios.default = axios;
|
|
||||||
|
|
||||||
// this module should only have a default export
|
|
||||||
export default axios
|
|
||||||
|
|
|
@ -1,121 +1,57 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import CanceledError from './CanceledError.js';
|
var Cancel = require('./Cancel');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A `CancelToken` is an object that can be used to request cancellation of an operation.
|
* A `CancelToken` is an object that can be used to request cancellation of an operation.
|
||||||
*
|
*
|
||||||
|
* @class
|
||||||
* @param {Function} executor The executor function.
|
* @param {Function} executor The executor function.
|
||||||
*
|
|
||||||
* @returns {CancelToken}
|
|
||||||
*/
|
*/
|
||||||
class CancelToken {
|
function CancelToken(executor) {
|
||||||
constructor(executor) {
|
if (typeof executor !== 'function') {
|
||||||
if (typeof executor !== 'function') {
|
throw new TypeError('executor must be a function.');
|
||||||
throw new TypeError('executor must be a function.');
|
|
||||||
}
|
|
||||||
|
|
||||||
let resolvePromise;
|
|
||||||
|
|
||||||
this.promise = new Promise(function promiseExecutor(resolve) {
|
|
||||||
resolvePromise = resolve;
|
|
||||||
});
|
|
||||||
|
|
||||||
const token = this;
|
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
|
||||||
this.promise.then(cancel => {
|
|
||||||
if (!token._listeners) return;
|
|
||||||
|
|
||||||
let i = token._listeners.length;
|
|
||||||
|
|
||||||
while (i-- > 0) {
|
|
||||||
token._listeners[i](cancel);
|
|
||||||
}
|
|
||||||
token._listeners = null;
|
|
||||||
});
|
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
|
||||||
this.promise.then = onfulfilled => {
|
|
||||||
let _resolve;
|
|
||||||
// eslint-disable-next-line func-names
|
|
||||||
const promise = new Promise(resolve => {
|
|
||||||
token.subscribe(resolve);
|
|
||||||
_resolve = resolve;
|
|
||||||
}).then(onfulfilled);
|
|
||||||
|
|
||||||
promise.cancel = function reject() {
|
|
||||||
token.unsubscribe(_resolve);
|
|
||||||
};
|
|
||||||
|
|
||||||
return promise;
|
|
||||||
};
|
|
||||||
|
|
||||||
executor(function cancel(message, config, request) {
|
|
||||||
if (token.reason) {
|
|
||||||
// Cancellation has already been requested
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
token.reason = new CanceledError(message, config, request);
|
|
||||||
resolvePromise(token.reason);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
var resolvePromise;
|
||||||
* Throws a `CanceledError` if cancellation has been requested.
|
this.promise = new Promise(function promiseExecutor(resolve) {
|
||||||
*/
|
resolvePromise = resolve;
|
||||||
throwIfRequested() {
|
});
|
||||||
if (this.reason) {
|
|
||||||
throw this.reason;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
var token = this;
|
||||||
* Subscribe to the cancel signal
|
executor(function cancel(message) {
|
||||||
*/
|
if (token.reason) {
|
||||||
|
// Cancellation has already been requested
|
||||||
subscribe(listener) {
|
|
||||||
if (this.reason) {
|
|
||||||
listener(this.reason);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this._listeners) {
|
token.reason = new Cancel(message);
|
||||||
this._listeners.push(listener);
|
resolvePromise(token.reason);
|
||||||
} else {
|
});
|
||||||
this._listeners = [listener];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Unsubscribe from the cancel signal
|
|
||||||
*/
|
|
||||||
|
|
||||||
unsubscribe(listener) {
|
|
||||||
if (!this._listeners) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const index = this._listeners.indexOf(listener);
|
|
||||||
if (index !== -1) {
|
|
||||||
this._listeners.splice(index, 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns an object that contains a new `CancelToken` and a function that, when called,
|
|
||||||
* cancels the `CancelToken`.
|
|
||||||
*/
|
|
||||||
static source() {
|
|
||||||
let cancel;
|
|
||||||
const token = new CancelToken(function executor(c) {
|
|
||||||
cancel = c;
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
token,
|
|
||||||
cancel
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default CancelToken;
|
/**
|
||||||
|
* Throws a `Cancel` if cancellation has been requested.
|
||||||
|
*/
|
||||||
|
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
|
||||||
|
if (this.reason) {
|
||||||
|
throw this.reason;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an object that contains a new `CancelToken` and a function that, when called,
|
||||||
|
* cancels the `CancelToken`.
|
||||||
|
*/
|
||||||
|
CancelToken.source = function source() {
|
||||||
|
var cancel;
|
||||||
|
var token = new CancelToken(function executor(c) {
|
||||||
|
cancel = c;
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
token: token,
|
||||||
|
cancel: cancel
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = CancelToken;
|
||||||
|
|
|
@ -1,25 +0,0 @@
|
||||||
'use strict';
|
|
||||||
|
|
||||||
import AxiosError from '../core/AxiosError.js';
|
|
||||||
import utils from '../utils.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A `CanceledError` is an object that is thrown when an operation is canceled.
|
|
||||||
*
|
|
||||||
* @param {string=} message The message.
|
|
||||||
* @param {Object=} config The config.
|
|
||||||
* @param {Object=} request The request.
|
|
||||||
*
|
|
||||||
* @returns {CanceledError} The created error.
|
|
||||||
*/
|
|
||||||
function CanceledError(message, config, request) {
|
|
||||||
// eslint-disable-next-line no-eq-null,eqeqeq
|
|
||||||
AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
|
|
||||||
this.name = 'CanceledError';
|
|
||||||
}
|
|
||||||
|
|
||||||
utils.inherits(CanceledError, AxiosError, {
|
|
||||||
__CANCEL__: true
|
|
||||||
});
|
|
||||||
|
|
||||||
export default CanceledError;
|
|
|
@ -1,5 +1,5 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
export default function isCancel(value) {
|
module.exports = function isCancel(value) {
|
||||||
return !!(value && value.__CANCEL__);
|
return !!(value && value.__CANCEL__);
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,201 +1,134 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import utils from './../utils.js';
|
var utils = require('./../utils');
|
||||||
import buildURL from '../helpers/buildURL.js';
|
var buildURL = require('../helpers/buildURL');
|
||||||
import InterceptorManager from './InterceptorManager.js';
|
var InterceptorManager = require('./InterceptorManager');
|
||||||
import dispatchRequest from './dispatchRequest.js';
|
var dispatchRequest = require('./dispatchRequest');
|
||||||
import mergeConfig from './mergeConfig.js';
|
var mergeConfig = require('./mergeConfig');
|
||||||
import buildFullPath from './buildFullPath.js';
|
var validator = require('../helpers/validator');
|
||||||
import validator from '../helpers/validator.js';
|
|
||||||
import AxiosHeaders from './AxiosHeaders.js';
|
|
||||||
|
|
||||||
const validators = validator.validators;
|
|
||||||
|
|
||||||
|
var validators = validator.validators;
|
||||||
/**
|
/**
|
||||||
* Create a new instance of Axios
|
* Create a new instance of Axios
|
||||||
*
|
*
|
||||||
* @param {Object} instanceConfig The default config for the instance
|
* @param {Object} instanceConfig The default config for the instance
|
||||||
*
|
|
||||||
* @return {Axios} A new instance of Axios
|
|
||||||
*/
|
*/
|
||||||
class Axios {
|
function Axios(instanceConfig) {
|
||||||
constructor(instanceConfig) {
|
this.defaults = instanceConfig;
|
||||||
this.defaults = instanceConfig;
|
this.interceptors = {
|
||||||
this.interceptors = {
|
request: new InterceptorManager(),
|
||||||
request: new InterceptorManager(),
|
response: new InterceptorManager()
|
||||||
response: new InterceptorManager()
|
};
|
||||||
};
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dispatch a request
|
||||||
|
*
|
||||||
|
* @param {Object} config The config specific for this request (merged with this.defaults)
|
||||||
|
*/
|
||||||
|
Axios.prototype.request = function request(config) {
|
||||||
|
/*eslint no-param-reassign:0*/
|
||||||
|
// Allow for axios('example/url'[, config]) a la fetch API
|
||||||
|
if (typeof config === 'string') {
|
||||||
|
config = arguments[1] || {};
|
||||||
|
config.url = arguments[0];
|
||||||
|
} else {
|
||||||
|
config = config || {};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
config = mergeConfig(this.defaults, config);
|
||||||
* Dispatch a request
|
|
||||||
*
|
|
||||||
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
|
|
||||||
* @param {?Object} config
|
|
||||||
*
|
|
||||||
* @returns {Promise} The Promise to be fulfilled
|
|
||||||
*/
|
|
||||||
async request(configOrUrl, config) {
|
|
||||||
try {
|
|
||||||
return await this._request(configOrUrl, config);
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof Error) {
|
|
||||||
let dummy;
|
|
||||||
|
|
||||||
Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());
|
// Set config.method
|
||||||
|
if (config.method) {
|
||||||
// slice off the Error: ... line
|
config.method = config.method.toLowerCase();
|
||||||
const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
|
} else if (this.defaults.method) {
|
||||||
|
config.method = this.defaults.method.toLowerCase();
|
||||||
if (!err.stack) {
|
} else {
|
||||||
err.stack = stack;
|
config.method = 'get';
|
||||||
// match without the 2 top stack lines
|
|
||||||
} else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
|
|
||||||
err.stack += '\n' + stack
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_request(configOrUrl, config) {
|
var transitional = config.transitional;
|
||||||
/*eslint no-param-reassign:0*/
|
|
||||||
// Allow for axios('example/url'[, config]) a la fetch API
|
if (transitional !== undefined) {
|
||||||
if (typeof configOrUrl === 'string') {
|
validator.assertOptions(transitional, {
|
||||||
config = config || {};
|
silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'),
|
||||||
config.url = configOrUrl;
|
forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'),
|
||||||
} else {
|
clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0')
|
||||||
config = configOrUrl || {};
|
}, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// filter out skipped interceptors
|
||||||
|
var requestInterceptorChain = [];
|
||||||
|
var synchronousRequestInterceptors = true;
|
||||||
|
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
|
||||||
|
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
config = mergeConfig(this.defaults, config);
|
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
|
||||||
|
|
||||||
const {transitional, paramsSerializer, headers} = config;
|
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
|
||||||
|
});
|
||||||
|
|
||||||
if (transitional !== undefined) {
|
var responseInterceptorChain = [];
|
||||||
validator.assertOptions(transitional, {
|
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
|
||||||
silentJSONParsing: validators.transitional(validators.boolean),
|
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
|
||||||
forcedJSONParsing: validators.transitional(validators.boolean),
|
});
|
||||||
clarifyTimeoutError: validators.transitional(validators.boolean)
|
|
||||||
}, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (paramsSerializer != null) {
|
var promise;
|
||||||
if (utils.isFunction(paramsSerializer)) {
|
|
||||||
config.paramsSerializer = {
|
|
||||||
serialize: paramsSerializer
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
validator.assertOptions(paramsSerializer, {
|
|
||||||
encode: validators.function,
|
|
||||||
serialize: validators.function
|
|
||||||
}, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set config.method
|
if (!synchronousRequestInterceptors) {
|
||||||
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
|
var chain = [dispatchRequest, undefined];
|
||||||
|
|
||||||
// Flatten headers
|
Array.prototype.unshift.apply(chain, requestInterceptorChain);
|
||||||
let contextHeaders = headers && utils.merge(
|
chain = chain.concat(responseInterceptorChain);
|
||||||
headers.common,
|
|
||||||
headers[config.method]
|
|
||||||
);
|
|
||||||
|
|
||||||
headers && utils.forEach(
|
promise = Promise.resolve(config);
|
||||||
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
|
while (chain.length) {
|
||||||
(method) => {
|
promise = promise.then(chain.shift(), chain.shift());
|
||||||
delete headers[method];
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
config.headers = AxiosHeaders.concat(contextHeaders, headers);
|
|
||||||
|
|
||||||
// filter out skipped interceptors
|
|
||||||
const requestInterceptorChain = [];
|
|
||||||
let synchronousRequestInterceptors = true;
|
|
||||||
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
|
|
||||||
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
|
|
||||||
|
|
||||||
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
|
|
||||||
});
|
|
||||||
|
|
||||||
const responseInterceptorChain = [];
|
|
||||||
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
|
|
||||||
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
|
|
||||||
});
|
|
||||||
|
|
||||||
let promise;
|
|
||||||
let i = 0;
|
|
||||||
let len;
|
|
||||||
|
|
||||||
if (!synchronousRequestInterceptors) {
|
|
||||||
const chain = [dispatchRequest.bind(this), undefined];
|
|
||||||
chain.unshift.apply(chain, requestInterceptorChain);
|
|
||||||
chain.push.apply(chain, responseInterceptorChain);
|
|
||||||
len = chain.length;
|
|
||||||
|
|
||||||
promise = Promise.resolve(config);
|
|
||||||
|
|
||||||
while (i < len) {
|
|
||||||
promise = promise.then(chain[i++], chain[i++]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return promise;
|
|
||||||
}
|
|
||||||
|
|
||||||
len = requestInterceptorChain.length;
|
|
||||||
|
|
||||||
let newConfig = config;
|
|
||||||
|
|
||||||
i = 0;
|
|
||||||
|
|
||||||
while (i < len) {
|
|
||||||
const onFulfilled = requestInterceptorChain[i++];
|
|
||||||
const onRejected = requestInterceptorChain[i++];
|
|
||||||
try {
|
|
||||||
newConfig = onFulfilled(newConfig);
|
|
||||||
} catch (error) {
|
|
||||||
onRejected.call(this, error);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
promise = dispatchRequest.call(this, newConfig);
|
|
||||||
} catch (error) {
|
|
||||||
return Promise.reject(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
i = 0;
|
|
||||||
len = responseInterceptorChain.length;
|
|
||||||
|
|
||||||
while (i < len) {
|
|
||||||
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return promise;
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
getUri(config) {
|
|
||||||
config = mergeConfig(this.defaults, config);
|
var newConfig = config;
|
||||||
const fullPath = buildFullPath(config.baseURL, config.url);
|
while (requestInterceptorChain.length) {
|
||||||
return buildURL(fullPath, config.params, config.paramsSerializer);
|
var onFulfilled = requestInterceptorChain.shift();
|
||||||
|
var onRejected = requestInterceptorChain.shift();
|
||||||
|
try {
|
||||||
|
newConfig = onFulfilled(newConfig);
|
||||||
|
} catch (error) {
|
||||||
|
onRejected(error);
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
try {
|
||||||
|
promise = dispatchRequest(newConfig);
|
||||||
|
} catch (error) {
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
while (responseInterceptorChain.length) {
|
||||||
|
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
|
||||||
|
}
|
||||||
|
|
||||||
|
return promise;
|
||||||
|
};
|
||||||
|
|
||||||
|
Axios.prototype.getUri = function getUri(config) {
|
||||||
|
config = mergeConfig(this.defaults, config);
|
||||||
|
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
|
||||||
|
};
|
||||||
|
|
||||||
// Provide aliases for supported request methods
|
// Provide aliases for supported request methods
|
||||||
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
|
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
|
||||||
/*eslint func-names:0*/
|
/*eslint func-names:0*/
|
||||||
Axios.prototype[method] = function(url, config) {
|
Axios.prototype[method] = function(url, config) {
|
||||||
return this.request(mergeConfig(config || {}, {
|
return this.request(mergeConfig(config || {}, {
|
||||||
method,
|
method: method,
|
||||||
url,
|
url: url,
|
||||||
data: (config || {}).data
|
data: (config || {}).data
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
|
@ -203,23 +136,13 @@ utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData
|
||||||
|
|
||||||
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
||||||
/*eslint func-names:0*/
|
/*eslint func-names:0*/
|
||||||
|
Axios.prototype[method] = function(url, data, config) {
|
||||||
function generateHTTPMethod(isForm) {
|
return this.request(mergeConfig(config || {}, {
|
||||||
return function httpMethod(url, data, config) {
|
method: method,
|
||||||
return this.request(mergeConfig(config || {}, {
|
url: url,
|
||||||
method,
|
data: data
|
||||||
headers: isForm ? {
|
}));
|
||||||
'Content-Type': 'multipart/form-data'
|
};
|
||||||
} : {},
|
|
||||||
url,
|
|
||||||
data
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
Axios.prototype[method] = generateHTTPMethod();
|
|
||||||
|
|
||||||
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export default Axios;
|
module.exports = Axios;
|
||||||
|
|
|
@ -1,100 +0,0 @@
|
||||||
'use strict';
|
|
||||||
|
|
||||||
import utils from '../utils.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create an Error with the specified message, config, error code, request and response.
|
|
||||||
*
|
|
||||||
* @param {string} message The error message.
|
|
||||||
* @param {string} [code] The error code (for example, 'ECONNABORTED').
|
|
||||||
* @param {Object} [config] The config.
|
|
||||||
* @param {Object} [request] The request.
|
|
||||||
* @param {Object} [response] The response.
|
|
||||||
*
|
|
||||||
* @returns {Error} The created error.
|
|
||||||
*/
|
|
||||||
function AxiosError(message, code, config, request, response) {
|
|
||||||
Error.call(this);
|
|
||||||
|
|
||||||
if (Error.captureStackTrace) {
|
|
||||||
Error.captureStackTrace(this, this.constructor);
|
|
||||||
} else {
|
|
||||||
this.stack = (new Error()).stack;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.message = message;
|
|
||||||
this.name = 'AxiosError';
|
|
||||||
code && (this.code = code);
|
|
||||||
config && (this.config = config);
|
|
||||||
request && (this.request = request);
|
|
||||||
response && (this.response = response);
|
|
||||||
}
|
|
||||||
|
|
||||||
utils.inherits(AxiosError, Error, {
|
|
||||||
toJSON: function toJSON() {
|
|
||||||
return {
|
|
||||||
// Standard
|
|
||||||
message: this.message,
|
|
||||||
name: this.name,
|
|
||||||
// Microsoft
|
|
||||||
description: this.description,
|
|
||||||
number: this.number,
|
|
||||||
// Mozilla
|
|
||||||
fileName: this.fileName,
|
|
||||||
lineNumber: this.lineNumber,
|
|
||||||
columnNumber: this.columnNumber,
|
|
||||||
stack: this.stack,
|
|
||||||
// Axios
|
|
||||||
config: utils.toJSONObject(this.config),
|
|
||||||
code: this.code,
|
|
||||||
status: this.response && this.response.status ? this.response.status : null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const prototype = AxiosError.prototype;
|
|
||||||
const descriptors = {};
|
|
||||||
|
|
||||||
[
|
|
||||||
'ERR_BAD_OPTION_VALUE',
|
|
||||||
'ERR_BAD_OPTION',
|
|
||||||
'ECONNABORTED',
|
|
||||||
'ETIMEDOUT',
|
|
||||||
'ERR_NETWORK',
|
|
||||||
'ERR_FR_TOO_MANY_REDIRECTS',
|
|
||||||
'ERR_DEPRECATED',
|
|
||||||
'ERR_BAD_RESPONSE',
|
|
||||||
'ERR_BAD_REQUEST',
|
|
||||||
'ERR_CANCELED',
|
|
||||||
'ERR_NOT_SUPPORT',
|
|
||||||
'ERR_INVALID_URL'
|
|
||||||
// eslint-disable-next-line func-names
|
|
||||||
].forEach(code => {
|
|
||||||
descriptors[code] = {value: code};
|
|
||||||
});
|
|
||||||
|
|
||||||
Object.defineProperties(AxiosError, descriptors);
|
|
||||||
Object.defineProperty(prototype, 'isAxiosError', {value: true});
|
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
|
||||||
AxiosError.from = (error, code, config, request, response, customProps) => {
|
|
||||||
const axiosError = Object.create(prototype);
|
|
||||||
|
|
||||||
utils.toFlatObject(error, axiosError, function filter(obj) {
|
|
||||||
return obj !== Error.prototype;
|
|
||||||
}, prop => {
|
|
||||||
return prop !== 'isAxiosError';
|
|
||||||
});
|
|
||||||
|
|
||||||
AxiosError.call(axiosError, error.message, code, config, request, response);
|
|
||||||
|
|
||||||
axiosError.cause = error;
|
|
||||||
|
|
||||||
axiosError.name = error.name;
|
|
||||||
|
|
||||||
customProps && Object.assign(axiosError, customProps);
|
|
||||||
|
|
||||||
return axiosError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default AxiosError;
|
|
|
@ -1,298 +0,0 @@
|
||||||
'use strict';
|
|
||||||
|
|
||||||
import utils from '../utils.js';
|
|
||||||
import parseHeaders from '../helpers/parseHeaders.js';
|
|
||||||
|
|
||||||
const $internals = Symbol('internals');
|
|
||||||
|
|
||||||
function normalizeHeader(header) {
|
|
||||||
return header && String(header).trim().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeValue(value) {
|
|
||||||
if (value === false || value == null) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return utils.isArray(value) ? value.map(normalizeValue) : String(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseTokens(str) {
|
|
||||||
const tokens = Object.create(null);
|
|
||||||
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
|
|
||||||
let match;
|
|
||||||
|
|
||||||
while ((match = tokensRE.exec(str))) {
|
|
||||||
tokens[match[1]] = match[2];
|
|
||||||
}
|
|
||||||
|
|
||||||
return tokens;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
|
|
||||||
|
|
||||||
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
|
|
||||||
if (utils.isFunction(filter)) {
|
|
||||||
return filter.call(this, value, header);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isHeaderNameFilter) {
|
|
||||||
value = header;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!utils.isString(value)) return;
|
|
||||||
|
|
||||||
if (utils.isString(filter)) {
|
|
||||||
return value.indexOf(filter) !== -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (utils.isRegExp(filter)) {
|
|
||||||
return filter.test(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatHeader(header) {
|
|
||||||
return header.trim()
|
|
||||||
.toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
|
|
||||||
return char.toUpperCase() + str;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildAccessors(obj, header) {
|
|
||||||
const accessorName = utils.toCamelCase(' ' + header);
|
|
||||||
|
|
||||||
['get', 'set', 'has'].forEach(methodName => {
|
|
||||||
Object.defineProperty(obj, methodName + accessorName, {
|
|
||||||
value: function(arg1, arg2, arg3) {
|
|
||||||
return this[methodName].call(this, header, arg1, arg2, arg3);
|
|
||||||
},
|
|
||||||
configurable: true
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
class AxiosHeaders {
|
|
||||||
constructor(headers) {
|
|
||||||
headers && this.set(headers);
|
|
||||||
}
|
|
||||||
|
|
||||||
set(header, valueOrRewrite, rewrite) {
|
|
||||||
const self = this;
|
|
||||||
|
|
||||||
function setHeader(_value, _header, _rewrite) {
|
|
||||||
const lHeader = normalizeHeader(_header);
|
|
||||||
|
|
||||||
if (!lHeader) {
|
|
||||||
throw new Error('header name must be a non-empty string');
|
|
||||||
}
|
|
||||||
|
|
||||||
const key = utils.findKey(self, lHeader);
|
|
||||||
|
|
||||||
if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
|
|
||||||
self[key || _header] = normalizeValue(_value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const setHeaders = (headers, _rewrite) =>
|
|
||||||
utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
|
|
||||||
|
|
||||||
if (utils.isPlainObject(header) || header instanceof this.constructor) {
|
|
||||||
setHeaders(header, valueOrRewrite)
|
|
||||||
} else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
|
|
||||||
setHeaders(parseHeaders(header), valueOrRewrite);
|
|
||||||
} else {
|
|
||||||
header != null && setHeader(valueOrRewrite, header, rewrite);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
get(header, parser) {
|
|
||||||
header = normalizeHeader(header);
|
|
||||||
|
|
||||||
if (header) {
|
|
||||||
const key = utils.findKey(this, header);
|
|
||||||
|
|
||||||
if (key) {
|
|
||||||
const value = this[key];
|
|
||||||
|
|
||||||
if (!parser) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parser === true) {
|
|
||||||
return parseTokens(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (utils.isFunction(parser)) {
|
|
||||||
return parser.call(this, value, key);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (utils.isRegExp(parser)) {
|
|
||||||
return parser.exec(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new TypeError('parser must be boolean|regexp|function');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
has(header, matcher) {
|
|
||||||
header = normalizeHeader(header);
|
|
||||||
|
|
||||||
if (header) {
|
|
||||||
const key = utils.findKey(this, header);
|
|
||||||
|
|
||||||
return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
delete(header, matcher) {
|
|
||||||
const self = this;
|
|
||||||
let deleted = false;
|
|
||||||
|
|
||||||
function deleteHeader(_header) {
|
|
||||||
_header = normalizeHeader(_header);
|
|
||||||
|
|
||||||
if (_header) {
|
|
||||||
const key = utils.findKey(self, _header);
|
|
||||||
|
|
||||||
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
|
|
||||||
delete self[key];
|
|
||||||
|
|
||||||
deleted = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (utils.isArray(header)) {
|
|
||||||
header.forEach(deleteHeader);
|
|
||||||
} else {
|
|
||||||
deleteHeader(header);
|
|
||||||
}
|
|
||||||
|
|
||||||
return deleted;
|
|
||||||
}
|
|
||||||
|
|
||||||
clear(matcher) {
|
|
||||||
const keys = Object.keys(this);
|
|
||||||
let i = keys.length;
|
|
||||||
let deleted = false;
|
|
||||||
|
|
||||||
while (i--) {
|
|
||||||
const key = keys[i];
|
|
||||||
if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
|
|
||||||
delete this[key];
|
|
||||||
deleted = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return deleted;
|
|
||||||
}
|
|
||||||
|
|
||||||
normalize(format) {
|
|
||||||
const self = this;
|
|
||||||
const headers = {};
|
|
||||||
|
|
||||||
utils.forEach(this, (value, header) => {
|
|
||||||
const key = utils.findKey(headers, header);
|
|
||||||
|
|
||||||
if (key) {
|
|
||||||
self[key] = normalizeValue(value);
|
|
||||||
delete self[header];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const normalized = format ? formatHeader(header) : String(header).trim();
|
|
||||||
|
|
||||||
if (normalized !== header) {
|
|
||||||
delete self[header];
|
|
||||||
}
|
|
||||||
|
|
||||||
self[normalized] = normalizeValue(value);
|
|
||||||
|
|
||||||
headers[normalized] = true;
|
|
||||||
});
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
concat(...targets) {
|
|
||||||
return this.constructor.concat(this, ...targets);
|
|
||||||
}
|
|
||||||
|
|
||||||
toJSON(asStrings) {
|
|
||||||
const obj = Object.create(null);
|
|
||||||
|
|
||||||
utils.forEach(this, (value, header) => {
|
|
||||||
value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);
|
|
||||||
});
|
|
||||||
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
|
|
||||||
[Symbol.iterator]() {
|
|
||||||
return Object.entries(this.toJSON())[Symbol.iterator]();
|
|
||||||
}
|
|
||||||
|
|
||||||
toString() {
|
|
||||||
return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
get [Symbol.toStringTag]() {
|
|
||||||
return 'AxiosHeaders';
|
|
||||||
}
|
|
||||||
|
|
||||||
static from(thing) {
|
|
||||||
return thing instanceof this ? thing : new this(thing);
|
|
||||||
}
|
|
||||||
|
|
||||||
static concat(first, ...targets) {
|
|
||||||
const computed = new this(first);
|
|
||||||
|
|
||||||
targets.forEach((target) => computed.set(target));
|
|
||||||
|
|
||||||
return computed;
|
|
||||||
}
|
|
||||||
|
|
||||||
static accessor(header) {
|
|
||||||
const internals = this[$internals] = (this[$internals] = {
|
|
||||||
accessors: {}
|
|
||||||
});
|
|
||||||
|
|
||||||
const accessors = internals.accessors;
|
|
||||||
const prototype = this.prototype;
|
|
||||||
|
|
||||||
function defineAccessor(_header) {
|
|
||||||
const lHeader = normalizeHeader(_header);
|
|
||||||
|
|
||||||
if (!accessors[lHeader]) {
|
|
||||||
buildAccessors(prototype, _header);
|
|
||||||
accessors[lHeader] = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
|
|
||||||
|
|
||||||
// reserved names hotfix
|
|
||||||
utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
|
|
||||||
let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
|
|
||||||
return {
|
|
||||||
get: () => value,
|
|
||||||
set(headerValue) {
|
|
||||||
this[mapped] = headerValue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
utils.freezeMethods(AxiosHeaders);
|
|
||||||
|
|
||||||
export default AxiosHeaders;
|
|
|
@ -1,71 +1,54 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import utils from './../utils.js';
|
var utils = require('./../utils');
|
||||||
|
|
||||||
class InterceptorManager {
|
function InterceptorManager() {
|
||||||
constructor() {
|
this.handlers = [];
|
||||||
this.handlers = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a new interceptor to the stack
|
|
||||||
*
|
|
||||||
* @param {Function} fulfilled The function to handle `then` for a `Promise`
|
|
||||||
* @param {Function} rejected The function to handle `reject` for a `Promise`
|
|
||||||
*
|
|
||||||
* @return {Number} An ID used to remove interceptor later
|
|
||||||
*/
|
|
||||||
use(fulfilled, rejected, options) {
|
|
||||||
this.handlers.push({
|
|
||||||
fulfilled,
|
|
||||||
rejected,
|
|
||||||
synchronous: options ? options.synchronous : false,
|
|
||||||
runWhen: options ? options.runWhen : null
|
|
||||||
});
|
|
||||||
return this.handlers.length - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove an interceptor from the stack
|
|
||||||
*
|
|
||||||
* @param {Number} id The ID that was returned by `use`
|
|
||||||
*
|
|
||||||
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
|
|
||||||
*/
|
|
||||||
eject(id) {
|
|
||||||
if (this.handlers[id]) {
|
|
||||||
this.handlers[id] = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clear all interceptors from the stack
|
|
||||||
*
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
clear() {
|
|
||||||
if (this.handlers) {
|
|
||||||
this.handlers = [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Iterate over all the registered interceptors
|
|
||||||
*
|
|
||||||
* This method is particularly useful for skipping over any
|
|
||||||
* interceptors that may have become `null` calling `eject`.
|
|
||||||
*
|
|
||||||
* @param {Function} fn The function to call for each interceptor
|
|
||||||
*
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
forEach(fn) {
|
|
||||||
utils.forEach(this.handlers, function forEachHandler(h) {
|
|
||||||
if (h !== null) {
|
|
||||||
fn(h);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default InterceptorManager;
|
/**
|
||||||
|
* Add a new interceptor to the stack
|
||||||
|
*
|
||||||
|
* @param {Function} fulfilled The function to handle `then` for a `Promise`
|
||||||
|
* @param {Function} rejected The function to handle `reject` for a `Promise`
|
||||||
|
*
|
||||||
|
* @return {Number} An ID used to remove interceptor later
|
||||||
|
*/
|
||||||
|
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
|
||||||
|
this.handlers.push({
|
||||||
|
fulfilled: fulfilled,
|
||||||
|
rejected: rejected,
|
||||||
|
synchronous: options ? options.synchronous : false,
|
||||||
|
runWhen: options ? options.runWhen : null
|
||||||
|
});
|
||||||
|
return this.handlers.length - 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove an interceptor from the stack
|
||||||
|
*
|
||||||
|
* @param {Number} id The ID that was returned by `use`
|
||||||
|
*/
|
||||||
|
InterceptorManager.prototype.eject = function eject(id) {
|
||||||
|
if (this.handlers[id]) {
|
||||||
|
this.handlers[id] = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Iterate over all the registered interceptors
|
||||||
|
*
|
||||||
|
* This method is particularly useful for skipping over any
|
||||||
|
* interceptors that may have become `null` calling `eject`.
|
||||||
|
*
|
||||||
|
* @param {Function} fn The function to call for each interceptor
|
||||||
|
*/
|
||||||
|
InterceptorManager.prototype.forEach = function forEach(fn) {
|
||||||
|
utils.forEach(this.handlers, function forEachHandler(h) {
|
||||||
|
if (h !== null) {
|
||||||
|
fn(h);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = InterceptorManager;
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import isAbsoluteURL from '../helpers/isAbsoluteURL.js';
|
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
|
||||||
import combineURLs from '../helpers/combineURLs.js';
|
var combineURLs = require('../helpers/combineURLs');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new URL by combining the baseURL with the requestedURL,
|
* Creates a new URL by combining the baseURL with the requestedURL,
|
||||||
|
@ -10,12 +10,11 @@ import combineURLs from '../helpers/combineURLs.js';
|
||||||
*
|
*
|
||||||
* @param {string} baseURL The base URL
|
* @param {string} baseURL The base URL
|
||||||
* @param {string} requestedURL Absolute or relative URL to combine
|
* @param {string} requestedURL Absolute or relative URL to combine
|
||||||
*
|
|
||||||
* @returns {string} The combined full path
|
* @returns {string} The combined full path
|
||||||
*/
|
*/
|
||||||
export default function buildFullPath(baseURL, requestedURL) {
|
module.exports = function buildFullPath(baseURL, requestedURL) {
|
||||||
if (baseURL && !isAbsoluteURL(requestedURL)) {
|
if (baseURL && !isAbsoluteURL(requestedURL)) {
|
||||||
return combineURLs(baseURL, requestedURL);
|
return combineURLs(baseURL, requestedURL);
|
||||||
}
|
}
|
||||||
return requestedURL;
|
return requestedURL;
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,52 +1,54 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import transformData from './transformData.js';
|
var utils = require('./../utils');
|
||||||
import isCancel from '../cancel/isCancel.js';
|
var transformData = require('./transformData');
|
||||||
import defaults from '../defaults/index.js';
|
var isCancel = require('../cancel/isCancel');
|
||||||
import CanceledError from '../cancel/CanceledError.js';
|
var defaults = require('../defaults');
|
||||||
import AxiosHeaders from '../core/AxiosHeaders.js';
|
|
||||||
import adapters from "../adapters/adapters.js";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Throws a `CanceledError` if cancellation has been requested.
|
* Throws a `Cancel` if cancellation has been requested.
|
||||||
*
|
|
||||||
* @param {Object} config The config that is to be used for the request
|
|
||||||
*
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
*/
|
||||||
function throwIfCancellationRequested(config) {
|
function throwIfCancellationRequested(config) {
|
||||||
if (config.cancelToken) {
|
if (config.cancelToken) {
|
||||||
config.cancelToken.throwIfRequested();
|
config.cancelToken.throwIfRequested();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.signal && config.signal.aborted) {
|
|
||||||
throw new CanceledError(null, config);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dispatch a request to the server using the configured adapter.
|
* Dispatch a request to the server using the configured adapter.
|
||||||
*
|
*
|
||||||
* @param {object} config The config that is to be used for the request
|
* @param {object} config The config that is to be used for the request
|
||||||
*
|
|
||||||
* @returns {Promise} The Promise to be fulfilled
|
* @returns {Promise} The Promise to be fulfilled
|
||||||
*/
|
*/
|
||||||
export default function dispatchRequest(config) {
|
module.exports = function dispatchRequest(config) {
|
||||||
throwIfCancellationRequested(config);
|
throwIfCancellationRequested(config);
|
||||||
|
|
||||||
config.headers = AxiosHeaders.from(config.headers);
|
// Ensure headers exist
|
||||||
|
config.headers = config.headers || {};
|
||||||
|
|
||||||
// Transform request data
|
// Transform request data
|
||||||
config.data = transformData.call(
|
config.data = transformData.call(
|
||||||
config,
|
config,
|
||||||
|
config.data,
|
||||||
|
config.headers,
|
||||||
config.transformRequest
|
config.transformRequest
|
||||||
);
|
);
|
||||||
|
|
||||||
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
|
// Flatten headers
|
||||||
config.headers.setContentType('application/x-www-form-urlencoded', false);
|
config.headers = utils.merge(
|
||||||
}
|
config.headers.common || {},
|
||||||
|
config.headers[config.method] || {},
|
||||||
|
config.headers
|
||||||
|
);
|
||||||
|
|
||||||
const adapter = adapters.getAdapter(config.adapter || defaults.adapter);
|
utils.forEach(
|
||||||
|
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
|
||||||
|
function cleanHeaderConfig(method) {
|
||||||
|
delete config.headers[method];
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
var adapter = config.adapter || defaults.adapter;
|
||||||
|
|
||||||
return adapter(config).then(function onAdapterResolution(response) {
|
return adapter(config).then(function onAdapterResolution(response) {
|
||||||
throwIfCancellationRequested(config);
|
throwIfCancellationRequested(config);
|
||||||
|
@ -54,12 +56,11 @@ export default function dispatchRequest(config) {
|
||||||
// Transform response data
|
// Transform response data
|
||||||
response.data = transformData.call(
|
response.data = transformData.call(
|
||||||
config,
|
config,
|
||||||
config.transformResponse,
|
response.data,
|
||||||
response
|
response.headers,
|
||||||
|
config.transformResponse
|
||||||
);
|
);
|
||||||
|
|
||||||
response.headers = AxiosHeaders.from(response.headers);
|
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}, function onAdapterRejection(reason) {
|
}, function onAdapterRejection(reason) {
|
||||||
if (!isCancel(reason)) {
|
if (!isCancel(reason)) {
|
||||||
|
@ -69,13 +70,13 @@ export default function dispatchRequest(config) {
|
||||||
if (reason && reason.response) {
|
if (reason && reason.response) {
|
||||||
reason.response.data = transformData.call(
|
reason.response.data = transformData.call(
|
||||||
config,
|
config,
|
||||||
config.transformResponse,
|
reason.response.data,
|
||||||
reason.response
|
reason.response.headers,
|
||||||
|
config.transformResponse
|
||||||
);
|
);
|
||||||
reason.response.headers = AxiosHeaders.from(reason.response.headers);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Promise.reject(reason);
|
return Promise.reject(reason);
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,9 +1,6 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import utils from '../utils.js';
|
var utils = require('../utils');
|
||||||
import AxiosHeaders from "./AxiosHeaders.js";
|
|
||||||
|
|
||||||
const headersToObject = (thing) => thing instanceof AxiosHeaders ? thing.toJSON() : thing;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Config-specific merge-function which creates a new config-object
|
* Config-specific merge-function which creates a new config-object
|
||||||
|
@ -11,17 +8,27 @@ const headersToObject = (thing) => thing instanceof AxiosHeaders ? thing.toJSON(
|
||||||
*
|
*
|
||||||
* @param {Object} config1
|
* @param {Object} config1
|
||||||
* @param {Object} config2
|
* @param {Object} config2
|
||||||
*
|
|
||||||
* @returns {Object} New object resulting from merging config2 to config1
|
* @returns {Object} New object resulting from merging config2 to config1
|
||||||
*/
|
*/
|
||||||
export default function mergeConfig(config1, config2) {
|
module.exports = function mergeConfig(config1, config2) {
|
||||||
// eslint-disable-next-line no-param-reassign
|
// eslint-disable-next-line no-param-reassign
|
||||||
config2 = config2 || {};
|
config2 = config2 || {};
|
||||||
const config = {};
|
var config = {};
|
||||||
|
|
||||||
function getMergedValue(target, source, caseless) {
|
var valueFromConfig2Keys = ['url', 'method', 'data'];
|
||||||
|
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
|
||||||
|
var defaultToConfig2Keys = [
|
||||||
|
'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
|
||||||
|
'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
|
||||||
|
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
|
||||||
|
'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
|
||||||
|
'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
|
||||||
|
];
|
||||||
|
var directMergeKeys = ['validateStatus'];
|
||||||
|
|
||||||
|
function getMergedValue(target, source) {
|
||||||
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
|
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
|
||||||
return utils.merge.call({caseless}, target, source);
|
return utils.merge(target, source);
|
||||||
} else if (utils.isPlainObject(source)) {
|
} else if (utils.isPlainObject(source)) {
|
||||||
return utils.merge({}, source);
|
return utils.merge({}, source);
|
||||||
} else if (utils.isArray(source)) {
|
} else if (utils.isArray(source)) {
|
||||||
|
@ -30,77 +37,51 @@ export default function mergeConfig(config1, config2) {
|
||||||
return source;
|
return source;
|
||||||
}
|
}
|
||||||
|
|
||||||
// eslint-disable-next-line consistent-return
|
function mergeDeepProperties(prop) {
|
||||||
function mergeDeepProperties(a, b, caseless) {
|
if (!utils.isUndefined(config2[prop])) {
|
||||||
if (!utils.isUndefined(b)) {
|
config[prop] = getMergedValue(config1[prop], config2[prop]);
|
||||||
return getMergedValue(a, b, caseless);
|
} else if (!utils.isUndefined(config1[prop])) {
|
||||||
} else if (!utils.isUndefined(a)) {
|
config[prop] = getMergedValue(undefined, config1[prop]);
|
||||||
return getMergedValue(undefined, a, caseless);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// eslint-disable-next-line consistent-return
|
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
|
||||||
function valueFromConfig2(a, b) {
|
if (!utils.isUndefined(config2[prop])) {
|
||||||
if (!utils.isUndefined(b)) {
|
config[prop] = getMergedValue(undefined, config2[prop]);
|
||||||
return getMergedValue(undefined, b);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line consistent-return
|
|
||||||
function defaultToConfig2(a, b) {
|
|
||||||
if (!utils.isUndefined(b)) {
|
|
||||||
return getMergedValue(undefined, b);
|
|
||||||
} else if (!utils.isUndefined(a)) {
|
|
||||||
return getMergedValue(undefined, a);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line consistent-return
|
|
||||||
function mergeDirectKeys(a, b, prop) {
|
|
||||||
if (prop in config2) {
|
|
||||||
return getMergedValue(a, b);
|
|
||||||
} else if (prop in config1) {
|
|
||||||
return getMergedValue(undefined, a);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeMap = {
|
|
||||||
url: valueFromConfig2,
|
|
||||||
method: valueFromConfig2,
|
|
||||||
data: valueFromConfig2,
|
|
||||||
baseURL: defaultToConfig2,
|
|
||||||
transformRequest: defaultToConfig2,
|
|
||||||
transformResponse: defaultToConfig2,
|
|
||||||
paramsSerializer: defaultToConfig2,
|
|
||||||
timeout: defaultToConfig2,
|
|
||||||
timeoutMessage: defaultToConfig2,
|
|
||||||
withCredentials: defaultToConfig2,
|
|
||||||
withXSRFToken: defaultToConfig2,
|
|
||||||
adapter: defaultToConfig2,
|
|
||||||
responseType: defaultToConfig2,
|
|
||||||
xsrfCookieName: defaultToConfig2,
|
|
||||||
xsrfHeaderName: defaultToConfig2,
|
|
||||||
onUploadProgress: defaultToConfig2,
|
|
||||||
onDownloadProgress: defaultToConfig2,
|
|
||||||
decompress: defaultToConfig2,
|
|
||||||
maxContentLength: defaultToConfig2,
|
|
||||||
maxBodyLength: defaultToConfig2,
|
|
||||||
beforeRedirect: defaultToConfig2,
|
|
||||||
transport: defaultToConfig2,
|
|
||||||
httpAgent: defaultToConfig2,
|
|
||||||
httpsAgent: defaultToConfig2,
|
|
||||||
cancelToken: defaultToConfig2,
|
|
||||||
socketPath: defaultToConfig2,
|
|
||||||
responseEncoding: defaultToConfig2,
|
|
||||||
validateStatus: mergeDirectKeys,
|
|
||||||
headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
|
|
||||||
};
|
|
||||||
|
|
||||||
utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
|
|
||||||
const merge = mergeMap[prop] || mergeDeepProperties;
|
|
||||||
const configValue = merge(config1[prop], config2[prop], prop);
|
|
||||||
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
|
||||||
|
|
||||||
|
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
|
||||||
|
if (!utils.isUndefined(config2[prop])) {
|
||||||
|
config[prop] = getMergedValue(undefined, config2[prop]);
|
||||||
|
} else if (!utils.isUndefined(config1[prop])) {
|
||||||
|
config[prop] = getMergedValue(undefined, config1[prop]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
utils.forEach(directMergeKeys, function merge(prop) {
|
||||||
|
if (prop in config2) {
|
||||||
|
config[prop] = getMergedValue(config1[prop], config2[prop]);
|
||||||
|
} else if (prop in config1) {
|
||||||
|
config[prop] = getMergedValue(undefined, config1[prop]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
var axiosKeys = valueFromConfig2Keys
|
||||||
|
.concat(mergeDeepPropertiesKeys)
|
||||||
|
.concat(defaultToConfig2Keys)
|
||||||
|
.concat(directMergeKeys);
|
||||||
|
|
||||||
|
var otherKeys = Object
|
||||||
|
.keys(config1)
|
||||||
|
.concat(Object.keys(config2))
|
||||||
|
.filter(function filterAxiosKeys(key) {
|
||||||
|
return axiosKeys.indexOf(key) === -1;
|
||||||
|
});
|
||||||
|
|
||||||
|
utils.forEach(otherKeys, mergeDeepProperties);
|
||||||
|
|
||||||
return config;
|
return config;
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import AxiosError from './AxiosError.js';
|
var createError = require('./createError');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve or reject a Promise based on response status.
|
* Resolve or reject a Promise based on response status.
|
||||||
|
@ -8,20 +8,18 @@ import AxiosError from './AxiosError.js';
|
||||||
* @param {Function} resolve A function that resolves the promise.
|
* @param {Function} resolve A function that resolves the promise.
|
||||||
* @param {Function} reject A function that rejects the promise.
|
* @param {Function} reject A function that rejects the promise.
|
||||||
* @param {object} response The response.
|
* @param {object} response The response.
|
||||||
*
|
|
||||||
* @returns {object} The response.
|
|
||||||
*/
|
*/
|
||||||
export default function settle(resolve, reject, response) {
|
module.exports = function settle(resolve, reject, response) {
|
||||||
const validateStatus = response.config.validateStatus;
|
var validateStatus = response.config.validateStatus;
|
||||||
if (!response.status || !validateStatus || validateStatus(response.status)) {
|
if (!response.status || !validateStatus || validateStatus(response.status)) {
|
||||||
resolve(response);
|
resolve(response);
|
||||||
} else {
|
} else {
|
||||||
reject(new AxiosError(
|
reject(createError(
|
||||||
'Request failed with status code ' + response.status,
|
'Request failed with status code ' + response.status,
|
||||||
[AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
|
|
||||||
response.config,
|
response.config,
|
||||||
|
null,
|
||||||
response.request,
|
response.request,
|
||||||
response
|
response
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,28 +1,22 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import utils from './../utils.js';
|
var utils = require('./../utils');
|
||||||
import defaults from '../defaults/index.js';
|
var defaults = require('./../defaults');
|
||||||
import AxiosHeaders from '../core/AxiosHeaders.js';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Transform the data for a request or a response
|
* Transform the data for a request or a response
|
||||||
*
|
*
|
||||||
|
* @param {Object|String} data The data to be transformed
|
||||||
|
* @param {Array} headers The headers for the request or response
|
||||||
* @param {Array|Function} fns A single function or Array of functions
|
* @param {Array|Function} fns A single function or Array of functions
|
||||||
* @param {?Object} response The response object
|
|
||||||
*
|
|
||||||
* @returns {*} The resulting transformed data
|
* @returns {*} The resulting transformed data
|
||||||
*/
|
*/
|
||||||
export default function transformData(fns, response) {
|
module.exports = function transformData(data, headers, fns) {
|
||||||
const config = this || defaults;
|
var context = this || defaults;
|
||||||
const context = response || config;
|
/*eslint no-param-reassign:0*/
|
||||||
const headers = AxiosHeaders.from(context.headers);
|
|
||||||
let data = context.data;
|
|
||||||
|
|
||||||
utils.forEach(fns, function transform(fn) {
|
utils.forEach(fns, function transform(fn) {
|
||||||
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
|
data = fn.call(context, data, headers);
|
||||||
});
|
});
|
||||||
|
|
||||||
headers.normalize();
|
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,156 +0,0 @@
|
||||||
'use strict';
|
|
||||||
|
|
||||||
import utils from '../utils.js';
|
|
||||||
import AxiosError from '../core/AxiosError.js';
|
|
||||||
import transitionalDefaults from './transitional.js';
|
|
||||||
import toFormData from '../helpers/toFormData.js';
|
|
||||||
import toURLEncodedForm from '../helpers/toURLEncodedForm.js';
|
|
||||||
import platform from '../platform/index.js';
|
|
||||||
import formDataToJSON from '../helpers/formDataToJSON.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
|
|
||||||
* of the input
|
|
||||||
*
|
|
||||||
* @param {any} rawValue - The value to be stringified.
|
|
||||||
* @param {Function} parser - A function that parses a string into a JavaScript object.
|
|
||||||
* @param {Function} encoder - A function that takes a value and returns a string.
|
|
||||||
*
|
|
||||||
* @returns {string} A stringified version of the rawValue.
|
|
||||||
*/
|
|
||||||
function stringifySafely(rawValue, parser, encoder) {
|
|
||||||
if (utils.isString(rawValue)) {
|
|
||||||
try {
|
|
||||||
(parser || JSON.parse)(rawValue);
|
|
||||||
return utils.trim(rawValue);
|
|
||||||
} catch (e) {
|
|
||||||
if (e.name !== 'SyntaxError') {
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (encoder || JSON.stringify)(rawValue);
|
|
||||||
}
|
|
||||||
|
|
||||||
const defaults = {
|
|
||||||
|
|
||||||
transitional: transitionalDefaults,
|
|
||||||
|
|
||||||
adapter: ['xhr', 'http'],
|
|
||||||
|
|
||||||
transformRequest: [function transformRequest(data, headers) {
|
|
||||||
const contentType = headers.getContentType() || '';
|
|
||||||
const hasJSONContentType = contentType.indexOf('application/json') > -1;
|
|
||||||
const isObjectPayload = utils.isObject(data);
|
|
||||||
|
|
||||||
if (isObjectPayload && utils.isHTMLForm(data)) {
|
|
||||||
data = new FormData(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
const isFormData = utils.isFormData(data);
|
|
||||||
|
|
||||||
if (isFormData) {
|
|
||||||
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (utils.isArrayBuffer(data) ||
|
|
||||||
utils.isBuffer(data) ||
|
|
||||||
utils.isStream(data) ||
|
|
||||||
utils.isFile(data) ||
|
|
||||||
utils.isBlob(data)
|
|
||||||
) {
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
if (utils.isArrayBufferView(data)) {
|
|
||||||
return data.buffer;
|
|
||||||
}
|
|
||||||
if (utils.isURLSearchParams(data)) {
|
|
||||||
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
|
|
||||||
return data.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
let isFileList;
|
|
||||||
|
|
||||||
if (isObjectPayload) {
|
|
||||||
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
|
|
||||||
return toURLEncodedForm(data, this.formSerializer).toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
|
|
||||||
const _FormData = this.env && this.env.FormData;
|
|
||||||
|
|
||||||
return toFormData(
|
|
||||||
isFileList ? {'files[]': data} : data,
|
|
||||||
_FormData && new _FormData(),
|
|
||||||
this.formSerializer
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isObjectPayload || hasJSONContentType ) {
|
|
||||||
headers.setContentType('application/json', false);
|
|
||||||
return stringifySafely(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}],
|
|
||||||
|
|
||||||
transformResponse: [function transformResponse(data) {
|
|
||||||
const transitional = this.transitional || defaults.transitional;
|
|
||||||
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
|
|
||||||
const JSONRequested = this.responseType === 'json';
|
|
||||||
|
|
||||||
if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
|
|
||||||
const silentJSONParsing = transitional && transitional.silentJSONParsing;
|
|
||||||
const strictJSONParsing = !silentJSONParsing && JSONRequested;
|
|
||||||
|
|
||||||
try {
|
|
||||||
return JSON.parse(data);
|
|
||||||
} catch (e) {
|
|
||||||
if (strictJSONParsing) {
|
|
||||||
if (e.name === 'SyntaxError') {
|
|
||||||
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
|
|
||||||
}
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}],
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A timeout in milliseconds to abort a request. If set to 0 (default) a
|
|
||||||
* timeout is not created.
|
|
||||||
*/
|
|
||||||
timeout: 0,
|
|
||||||
|
|
||||||
xsrfCookieName: 'XSRF-TOKEN',
|
|
||||||
xsrfHeaderName: 'X-XSRF-TOKEN',
|
|
||||||
|
|
||||||
maxContentLength: -1,
|
|
||||||
maxBodyLength: -1,
|
|
||||||
|
|
||||||
env: {
|
|
||||||
FormData: platform.classes.FormData,
|
|
||||||
Blob: platform.classes.Blob
|
|
||||||
},
|
|
||||||
|
|
||||||
validateStatus: function validateStatus(status) {
|
|
||||||
return status >= 200 && status < 300;
|
|
||||||
},
|
|
||||||
|
|
||||||
headers: {
|
|
||||||
common: {
|
|
||||||
'Accept': 'application/json, text/plain, */*',
|
|
||||||
'Content-Type': undefined
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
|
|
||||||
defaults.headers[method] = {};
|
|
||||||
});
|
|
||||||
|
|
||||||
export default defaults;
|
|
|
@ -1,7 +0,0 @@
|
||||||
'use strict';
|
|
||||||
|
|
||||||
export default {
|
|
||||||
silentJSONParsing: true,
|
|
||||||
forcedJSONParsing: true,
|
|
||||||
clarifyTimeoutError: false
|
|
||||||
};
|
|
|
@ -1,3 +0,0 @@
|
||||||
# axios // env
|
|
||||||
|
|
||||||
The `data.js` file is updated automatically when the package version is upgrading. Please do not edit it manually.
|
|
|
@ -1,2 +0,0 @@
|
||||||
import _FormData from 'form-data';
|
|
||||||
export default typeof FormData !== 'undefined' ? FormData : _FormData;
|
|
|
@ -1 +0,0 @@
|
||||||
export const VERSION = "1.6.7";
|
|
|
@ -1,191 +0,0 @@
|
||||||
'use strict';
|
|
||||||
|
|
||||||
import stream from 'stream';
|
|
||||||
import utils from '../utils.js';
|
|
||||||
import throttle from './throttle.js';
|
|
||||||
import speedometer from './speedometer.js';
|
|
||||||
|
|
||||||
const kInternals = Symbol('internals');
|
|
||||||
|
|
||||||
class AxiosTransformStream extends stream.Transform{
|
|
||||||
constructor(options) {
|
|
||||||
options = utils.toFlatObject(options, {
|
|
||||||
maxRate: 0,
|
|
||||||
chunkSize: 64 * 1024,
|
|
||||||
minChunkSize: 100,
|
|
||||||
timeWindow: 500,
|
|
||||||
ticksRate: 2,
|
|
||||||
samplesCount: 15
|
|
||||||
}, null, (prop, source) => {
|
|
||||||
return !utils.isUndefined(source[prop]);
|
|
||||||
});
|
|
||||||
|
|
||||||
super({
|
|
||||||
readableHighWaterMark: options.chunkSize
|
|
||||||
});
|
|
||||||
|
|
||||||
const self = this;
|
|
||||||
|
|
||||||
const internals = this[kInternals] = {
|
|
||||||
length: options.length,
|
|
||||||
timeWindow: options.timeWindow,
|
|
||||||
ticksRate: options.ticksRate,
|
|
||||||
chunkSize: options.chunkSize,
|
|
||||||
maxRate: options.maxRate,
|
|
||||||
minChunkSize: options.minChunkSize,
|
|
||||||
bytesSeen: 0,
|
|
||||||
isCaptured: false,
|
|
||||||
notifiedBytesLoaded: 0,
|
|
||||||
ts: Date.now(),
|
|
||||||
bytes: 0,
|
|
||||||
onReadCallback: null
|
|
||||||
};
|
|
||||||
|
|
||||||
const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow);
|
|
||||||
|
|
||||||
this.on('newListener', event => {
|
|
||||||
if (event === 'progress') {
|
|
||||||
if (!internals.isCaptured) {
|
|
||||||
internals.isCaptured = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let bytesNotified = 0;
|
|
||||||
|
|
||||||
internals.updateProgress = throttle(function throttledHandler() {
|
|
||||||
const totalBytes = internals.length;
|
|
||||||
const bytesTransferred = internals.bytesSeen;
|
|
||||||
const progressBytes = bytesTransferred - bytesNotified;
|
|
||||||
if (!progressBytes || self.destroyed) return;
|
|
||||||
|
|
||||||
const rate = _speedometer(progressBytes);
|
|
||||||
|
|
||||||
bytesNotified = bytesTransferred;
|
|
||||||
|
|
||||||
process.nextTick(() => {
|
|
||||||
self.emit('progress', {
|
|
||||||
'loaded': bytesTransferred,
|
|
||||||
'total': totalBytes,
|
|
||||||
'progress': totalBytes ? (bytesTransferred / totalBytes) : undefined,
|
|
||||||
'bytes': progressBytes,
|
|
||||||
'rate': rate ? rate : undefined,
|
|
||||||
'estimated': rate && totalBytes && bytesTransferred <= totalBytes ?
|
|
||||||
(totalBytes - bytesTransferred) / rate : undefined
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}, internals.ticksRate);
|
|
||||||
|
|
||||||
const onFinish = () => {
|
|
||||||
internals.updateProgress(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
this.once('end', onFinish);
|
|
||||||
this.once('error', onFinish);
|
|
||||||
}
|
|
||||||
|
|
||||||
_read(size) {
|
|
||||||
const internals = this[kInternals];
|
|
||||||
|
|
||||||
if (internals.onReadCallback) {
|
|
||||||
internals.onReadCallback();
|
|
||||||
}
|
|
||||||
|
|
||||||
return super._read(size);
|
|
||||||
}
|
|
||||||
|
|
||||||
_transform(chunk, encoding, callback) {
|
|
||||||
const self = this;
|
|
||||||
const internals = this[kInternals];
|
|
||||||
const maxRate = internals.maxRate;
|
|
||||||
|
|
||||||
const readableHighWaterMark = this.readableHighWaterMark;
|
|
||||||
|
|
||||||
const timeWindow = internals.timeWindow;
|
|
||||||
|
|
||||||
const divider = 1000 / timeWindow;
|
|
||||||
const bytesThreshold = (maxRate / divider);
|
|
||||||
const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
|
|
||||||
|
|
||||||
function pushChunk(_chunk, _callback) {
|
|
||||||
const bytes = Buffer.byteLength(_chunk);
|
|
||||||
internals.bytesSeen += bytes;
|
|
||||||
internals.bytes += bytes;
|
|
||||||
|
|
||||||
if (internals.isCaptured) {
|
|
||||||
internals.updateProgress();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (self.push(_chunk)) {
|
|
||||||
process.nextTick(_callback);
|
|
||||||
} else {
|
|
||||||
internals.onReadCallback = () => {
|
|
||||||
internals.onReadCallback = null;
|
|
||||||
process.nextTick(_callback);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const transformChunk = (_chunk, _callback) => {
|
|
||||||
const chunkSize = Buffer.byteLength(_chunk);
|
|
||||||
let chunkRemainder = null;
|
|
||||||
let maxChunkSize = readableHighWaterMark;
|
|
||||||
let bytesLeft;
|
|
||||||
let passed = 0;
|
|
||||||
|
|
||||||
if (maxRate) {
|
|
||||||
const now = Date.now();
|
|
||||||
|
|
||||||
if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) {
|
|
||||||
internals.ts = now;
|
|
||||||
bytesLeft = bytesThreshold - internals.bytes;
|
|
||||||
internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
|
|
||||||
passed = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
bytesLeft = bytesThreshold - internals.bytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (maxRate) {
|
|
||||||
if (bytesLeft <= 0) {
|
|
||||||
// next time window
|
|
||||||
return setTimeout(() => {
|
|
||||||
_callback(null, _chunk);
|
|
||||||
}, timeWindow - passed);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (bytesLeft < maxChunkSize) {
|
|
||||||
maxChunkSize = bytesLeft;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) {
|
|
||||||
chunkRemainder = _chunk.subarray(maxChunkSize);
|
|
||||||
_chunk = _chunk.subarray(0, maxChunkSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
pushChunk(_chunk, chunkRemainder ? () => {
|
|
||||||
process.nextTick(_callback, null, chunkRemainder);
|
|
||||||
} : _callback);
|
|
||||||
};
|
|
||||||
|
|
||||||
transformChunk(chunk, function transformNextChunk(err, _chunk) {
|
|
||||||
if (err) {
|
|
||||||
return callback(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_chunk) {
|
|
||||||
transformChunk(_chunk, transformNextChunk);
|
|
||||||
} else {
|
|
||||||
callback(null);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
setLength(length) {
|
|
||||||
this[kInternals].length = +length;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default AxiosTransformStream;
|
|
|
@ -1,58 +0,0 @@
|
||||||
'use strict';
|
|
||||||
|
|
||||||
import toFormData from './toFormData.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* It encodes a string by replacing all characters that are not in the unreserved set with
|
|
||||||
* their percent-encoded equivalents
|
|
||||||
*
|
|
||||||
* @param {string} str - The string to encode.
|
|
||||||
*
|
|
||||||
* @returns {string} The encoded string.
|
|
||||||
*/
|
|
||||||
function encode(str) {
|
|
||||||
const charMap = {
|
|
||||||
'!': '%21',
|
|
||||||
"'": '%27',
|
|
||||||
'(': '%28',
|
|
||||||
')': '%29',
|
|
||||||
'~': '%7E',
|
|
||||||
'%20': '+',
|
|
||||||
'%00': '\x00'
|
|
||||||
};
|
|
||||||
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
|
|
||||||
return charMap[match];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* It takes a params object and converts it to a FormData object
|
|
||||||
*
|
|
||||||
* @param {Object<string, any>} params - The parameters to be converted to a FormData object.
|
|
||||||
* @param {Object<string, any>} options - The options object passed to the Axios constructor.
|
|
||||||
*
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
function AxiosURLSearchParams(params, options) {
|
|
||||||
this._pairs = [];
|
|
||||||
|
|
||||||
params && toFormData(params, this, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
const prototype = AxiosURLSearchParams.prototype;
|
|
||||||
|
|
||||||
prototype.append = function append(name, value) {
|
|
||||||
this._pairs.push([name, value]);
|
|
||||||
};
|
|
||||||
|
|
||||||
prototype.toString = function toString(encoder) {
|
|
||||||
const _encode = encoder ? function(value) {
|
|
||||||
return encoder.call(this, value, encode);
|
|
||||||
} : encode;
|
|
||||||
|
|
||||||
return this._pairs.map(function each(pair) {
|
|
||||||
return _encode(pair[0]) + '=' + _encode(pair[1]);
|
|
||||||
}, '').join('&');
|
|
||||||
};
|
|
||||||
|
|
||||||
export default AxiosURLSearchParams;
|
|
|
@ -1,71 +0,0 @@
|
||||||
const HttpStatusCode = {
|
|
||||||
Continue: 100,
|
|
||||||
SwitchingProtocols: 101,
|
|
||||||
Processing: 102,
|
|
||||||
EarlyHints: 103,
|
|
||||||
Ok: 200,
|
|
||||||
Created: 201,
|
|
||||||
Accepted: 202,
|
|
||||||
NonAuthoritativeInformation: 203,
|
|
||||||
NoContent: 204,
|
|
||||||
ResetContent: 205,
|
|
||||||
PartialContent: 206,
|
|
||||||
MultiStatus: 207,
|
|
||||||
AlreadyReported: 208,
|
|
||||||
ImUsed: 226,
|
|
||||||
MultipleChoices: 300,
|
|
||||||
MovedPermanently: 301,
|
|
||||||
Found: 302,
|
|
||||||
SeeOther: 303,
|
|
||||||
NotModified: 304,
|
|
||||||
UseProxy: 305,
|
|
||||||
Unused: 306,
|
|
||||||
TemporaryRedirect: 307,
|
|
||||||
PermanentRedirect: 308,
|
|
||||||
BadRequest: 400,
|
|
||||||
Unauthorized: 401,
|
|
||||||
PaymentRequired: 402,
|
|
||||||
Forbidden: 403,
|
|
||||||
NotFound: 404,
|
|
||||||
MethodNotAllowed: 405,
|
|
||||||
NotAcceptable: 406,
|
|
||||||
ProxyAuthenticationRequired: 407,
|
|
||||||
RequestTimeout: 408,
|
|
||||||
Conflict: 409,
|
|
||||||
Gone: 410,
|
|
||||||
LengthRequired: 411,
|
|
||||||
PreconditionFailed: 412,
|
|
||||||
PayloadTooLarge: 413,
|
|
||||||
UriTooLong: 414,
|
|
||||||
UnsupportedMediaType: 415,
|
|
||||||
RangeNotSatisfiable: 416,
|
|
||||||
ExpectationFailed: 417,
|
|
||||||
ImATeapot: 418,
|
|
||||||
MisdirectedRequest: 421,
|
|
||||||
UnprocessableEntity: 422,
|
|
||||||
Locked: 423,
|
|
||||||
FailedDependency: 424,
|
|
||||||
TooEarly: 425,
|
|
||||||
UpgradeRequired: 426,
|
|
||||||
PreconditionRequired: 428,
|
|
||||||
TooManyRequests: 429,
|
|
||||||
RequestHeaderFieldsTooLarge: 431,
|
|
||||||
UnavailableForLegalReasons: 451,
|
|
||||||
InternalServerError: 500,
|
|
||||||
NotImplemented: 501,
|
|
||||||
BadGateway: 502,
|
|
||||||
ServiceUnavailable: 503,
|
|
||||||
GatewayTimeout: 504,
|
|
||||||
HttpVersionNotSupported: 505,
|
|
||||||
VariantAlsoNegotiates: 506,
|
|
||||||
InsufficientStorage: 507,
|
|
||||||
LoopDetected: 508,
|
|
||||||
NotExtended: 510,
|
|
||||||
NetworkAuthenticationRequired: 511,
|
|
||||||
};
|
|
||||||
|
|
||||||
Object.entries(HttpStatusCode).forEach(([key, value]) => {
|
|
||||||
HttpStatusCode[value] = key;
|
|
||||||
});
|
|
||||||
|
|
||||||
export default HttpStatusCode;
|
|
|
@ -1,28 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
import stream from "stream";
|
|
||||||
|
|
||||||
class ZlibHeaderTransformStream extends stream.Transform {
|
|
||||||
__transform(chunk, encoding, callback) {
|
|
||||||
this.push(chunk);
|
|
||||||
callback();
|
|
||||||
}
|
|
||||||
|
|
||||||
_transform(chunk, encoding, callback) {
|
|
||||||
if (chunk.length !== 0) {
|
|
||||||
this._transform = this.__transform;
|
|
||||||
|
|
||||||
// Add Default Compression headers if no zlib headers are present
|
|
||||||
if (chunk[0] !== 120) { // Hex: 78
|
|
||||||
const header = Buffer.alloc(2);
|
|
||||||
header[0] = 120; // Hex: 78
|
|
||||||
header[1] = 156; // Hex: 9C
|
|
||||||
this.push(header, encoding);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.__transform(chunk, encoding, callback);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default ZlibHeaderTransformStream;
|
|
|
@ -1,7 +1,11 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
export default function bind(fn, thisArg) {
|
module.exports = function bind(fn, thisArg) {
|
||||||
return function wrap() {
|
return function wrap() {
|
||||||
return fn.apply(thisArg, arguments);
|
var args = new Array(arguments.length);
|
||||||
|
for (var i = 0; i < args.length; i++) {
|
||||||
|
args[i] = arguments[i];
|
||||||
|
}
|
||||||
|
return fn.apply(thisArg, args);
|
||||||
};
|
};
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,16 +1,7 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import utils from '../utils.js';
|
var utils = require('./../utils');
|
||||||
import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
|
|
||||||
* URI encoded counterparts
|
|
||||||
*
|
|
||||||
* @param {string} val The value to be encoded.
|
|
||||||
*
|
|
||||||
* @returns {string} The encoded value.
|
|
||||||
*/
|
|
||||||
function encode(val) {
|
function encode(val) {
|
||||||
return encodeURIComponent(val).
|
return encodeURIComponent(val).
|
||||||
replace(/%3A/gi, ':').
|
replace(/%3A/gi, ':').
|
||||||
|
@ -26,38 +17,54 @@ function encode(val) {
|
||||||
*
|
*
|
||||||
* @param {string} url The base of the url (e.g., http://www.google.com)
|
* @param {string} url The base of the url (e.g., http://www.google.com)
|
||||||
* @param {object} [params] The params to be appended
|
* @param {object} [params] The params to be appended
|
||||||
* @param {?object} options
|
|
||||||
*
|
|
||||||
* @returns {string} The formatted url
|
* @returns {string} The formatted url
|
||||||
*/
|
*/
|
||||||
export default function buildURL(url, params, options) {
|
module.exports = function buildURL(url, params, paramsSerializer) {
|
||||||
/*eslint no-param-reassign:0*/
|
/*eslint no-param-reassign:0*/
|
||||||
if (!params) {
|
if (!params) {
|
||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
const _encode = options && options.encode || encode;
|
|
||||||
|
|
||||||
const serializeFn = options && options.serialize;
|
var serializedParams;
|
||||||
|
if (paramsSerializer) {
|
||||||
let serializedParams;
|
serializedParams = paramsSerializer(params);
|
||||||
|
} else if (utils.isURLSearchParams(params)) {
|
||||||
if (serializeFn) {
|
serializedParams = params.toString();
|
||||||
serializedParams = serializeFn(params, options);
|
|
||||||
} else {
|
} else {
|
||||||
serializedParams = utils.isURLSearchParams(params) ?
|
var parts = [];
|
||||||
params.toString() :
|
|
||||||
new AxiosURLSearchParams(params, options).toString(_encode);
|
utils.forEach(params, function serialize(val, key) {
|
||||||
|
if (val === null || typeof val === 'undefined') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (utils.isArray(val)) {
|
||||||
|
key = key + '[]';
|
||||||
|
} else {
|
||||||
|
val = [val];
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.forEach(val, function parseValue(v) {
|
||||||
|
if (utils.isDate(v)) {
|
||||||
|
v = v.toISOString();
|
||||||
|
} else if (utils.isObject(v)) {
|
||||||
|
v = JSON.stringify(v);
|
||||||
|
}
|
||||||
|
parts.push(encode(key) + '=' + encode(v));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
serializedParams = parts.join('&');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (serializedParams) {
|
if (serializedParams) {
|
||||||
const hashmarkIndex = url.indexOf("#");
|
var hashmarkIndex = url.indexOf('#');
|
||||||
|
|
||||||
if (hashmarkIndex !== -1) {
|
if (hashmarkIndex !== -1) {
|
||||||
url = url.slice(0, hashmarkIndex);
|
url = url.slice(0, hashmarkIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
|
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
|
||||||
}
|
}
|
||||||
|
|
||||||
return url;
|
return url;
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,16 +0,0 @@
|
||||||
import utils from "../utils.js";
|
|
||||||
|
|
||||||
const callbackify = (fn, reducer) => {
|
|
||||||
return utils.isAsyncFn(fn) ? function (...args) {
|
|
||||||
const cb = args.pop();
|
|
||||||
fn.apply(this, args).then((value) => {
|
|
||||||
try {
|
|
||||||
reducer ? cb(null, ...reducer(value)) : cb(null, value);
|
|
||||||
} catch (err) {
|
|
||||||
cb(err);
|
|
||||||
}
|
|
||||||
}, cb);
|
|
||||||
} : fn;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default callbackify;
|
|
|
@ -5,11 +5,10 @@
|
||||||
*
|
*
|
||||||
* @param {string} baseURL The base URL
|
* @param {string} baseURL The base URL
|
||||||
* @param {string} relativeURL The relative URL
|
* @param {string} relativeURL The relative URL
|
||||||
*
|
|
||||||
* @returns {string} The combined URL
|
* @returns {string} The combined URL
|
||||||
*/
|
*/
|
||||||
export default function combineURLs(baseURL, relativeURL) {
|
module.exports = function combineURLs(baseURL, relativeURL) {
|
||||||
return relativeURL
|
return relativeURL
|
||||||
? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
|
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
|
||||||
: baseURL;
|
: baseURL;
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,42 +1,53 @@
|
||||||
import utils from './../utils.js';
|
'use strict';
|
||||||
import platform from '../platform/index.js';
|
|
||||||
|
|
||||||
export default platform.hasStandardBrowserEnv ?
|
var utils = require('./../utils');
|
||||||
|
|
||||||
|
module.exports = (
|
||||||
|
utils.isStandardBrowserEnv() ?
|
||||||
|
|
||||||
// Standard browser envs support document.cookie
|
// Standard browser envs support document.cookie
|
||||||
{
|
(function standardBrowserEnv() {
|
||||||
write(name, value, expires, path, domain, secure) {
|
return {
|
||||||
const cookie = [name + '=' + encodeURIComponent(value)];
|
write: function write(name, value, expires, path, domain, secure) {
|
||||||
|
var cookie = [];
|
||||||
|
cookie.push(name + '=' + encodeURIComponent(value));
|
||||||
|
|
||||||
utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
|
if (utils.isNumber(expires)) {
|
||||||
|
cookie.push('expires=' + new Date(expires).toGMTString());
|
||||||
|
}
|
||||||
|
|
||||||
utils.isString(path) && cookie.push('path=' + path);
|
if (utils.isString(path)) {
|
||||||
|
cookie.push('path=' + path);
|
||||||
|
}
|
||||||
|
|
||||||
utils.isString(domain) && cookie.push('domain=' + domain);
|
if (utils.isString(domain)) {
|
||||||
|
cookie.push('domain=' + domain);
|
||||||
|
}
|
||||||
|
|
||||||
secure === true && cookie.push('secure');
|
if (secure === true) {
|
||||||
|
cookie.push('secure');
|
||||||
|
}
|
||||||
|
|
||||||
document.cookie = cookie.join('; ');
|
document.cookie = cookie.join('; ');
|
||||||
},
|
},
|
||||||
|
|
||||||
read(name) {
|
read: function read(name) {
|
||||||
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
|
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
|
||||||
return (match ? decodeURIComponent(match[3]) : null);
|
return (match ? decodeURIComponent(match[3]) : null);
|
||||||
},
|
},
|
||||||
|
|
||||||
remove(name) {
|
remove: function remove(name) {
|
||||||
this.write(name, '', Date.now() - 86400000);
|
this.write(name, '', Date.now() - 86400000);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
})() :
|
||||||
:
|
|
||||||
|
|
||||||
// Non-standard browser env (web workers, react-native) lack needed support.
|
|
||||||
{
|
|
||||||
write() {},
|
|
||||||
read() {
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
remove() {}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
// Non standard browser env (web workers, react-native) lack needed support.
|
||||||
|
(function nonStandardBrowserEnv() {
|
||||||
|
return {
|
||||||
|
write: function write() {},
|
||||||
|
read: function read() { return null; },
|
||||||
|
remove: function remove() {}
|
||||||
|
};
|
||||||
|
})()
|
||||||
|
);
|
||||||
|
|
|
@ -9,10 +9,8 @@
|
||||||
* @param {string} method The name of the deprecated method
|
* @param {string} method The name of the deprecated method
|
||||||
* @param {string} [instead] The alternate method to use if applicable
|
* @param {string} [instead] The alternate method to use if applicable
|
||||||
* @param {string} [docs] The documentation URL to get further details
|
* @param {string} [docs] The documentation URL to get further details
|
||||||
*
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
*/
|
||||||
export default function deprecatedMethod(method, instead, docs) {
|
module.exports = function deprecatedMethod(method, instead, docs) {
|
||||||
try {
|
try {
|
||||||
console.warn(
|
console.warn(
|
||||||
'DEPRECATED method `' + method + '`.' +
|
'DEPRECATED method `' + method + '`.' +
|
||||||
|
@ -23,4 +21,4 @@ export default function deprecatedMethod(method, instead, docs) {
|
||||||
console.warn('For more information about usage see ' + docs);
|
console.warn('For more information about usage see ' + docs);
|
||||||
}
|
}
|
||||||
} catch (e) { /* Ignore */ }
|
} catch (e) { /* Ignore */ }
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,95 +0,0 @@
|
||||||
'use strict';
|
|
||||||
|
|
||||||
import utils from '../utils.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
|
|
||||||
*
|
|
||||||
* @param {string} name - The name of the property to get.
|
|
||||||
*
|
|
||||||
* @returns An array of strings.
|
|
||||||
*/
|
|
||||||
function parsePropPath(name) {
|
|
||||||
// foo[x][y][z]
|
|
||||||
// foo.x.y.z
|
|
||||||
// foo-x-y-z
|
|
||||||
// foo x y z
|
|
||||||
return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
|
|
||||||
return match[0] === '[]' ? '' : match[1] || match[0];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert an array to an object.
|
|
||||||
*
|
|
||||||
* @param {Array<any>} arr - The array to convert to an object.
|
|
||||||
*
|
|
||||||
* @returns An object with the same keys and values as the array.
|
|
||||||
*/
|
|
||||||
function arrayToObject(arr) {
|
|
||||||
const obj = {};
|
|
||||||
const keys = Object.keys(arr);
|
|
||||||
let i;
|
|
||||||
const len = keys.length;
|
|
||||||
let key;
|
|
||||||
for (i = 0; i < len; i++) {
|
|
||||||
key = keys[i];
|
|
||||||
obj[key] = arr[key];
|
|
||||||
}
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* It takes a FormData object and returns a JavaScript object
|
|
||||||
*
|
|
||||||
* @param {string} formData The FormData object to convert to JSON.
|
|
||||||
*
|
|
||||||
* @returns {Object<string, any> | null} The converted object.
|
|
||||||
*/
|
|
||||||
function formDataToJSON(formData) {
|
|
||||||
function buildPath(path, value, target, index) {
|
|
||||||
let name = path[index++];
|
|
||||||
|
|
||||||
if (name === '__proto__') return true;
|
|
||||||
|
|
||||||
const isNumericKey = Number.isFinite(+name);
|
|
||||||
const isLast = index >= path.length;
|
|
||||||
name = !name && utils.isArray(target) ? target.length : name;
|
|
||||||
|
|
||||||
if (isLast) {
|
|
||||||
if (utils.hasOwnProp(target, name)) {
|
|
||||||
target[name] = [target[name], value];
|
|
||||||
} else {
|
|
||||||
target[name] = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return !isNumericKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!target[name] || !utils.isObject(target[name])) {
|
|
||||||
target[name] = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = buildPath(path, value, target[name], index);
|
|
||||||
|
|
||||||
if (result && utils.isArray(target[name])) {
|
|
||||||
target[name] = arrayToObject(target[name]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return !isNumericKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
|
|
||||||
const obj = {};
|
|
||||||
|
|
||||||
utils.forEachEntry(formData, (name, value) => {
|
|
||||||
buildPath(parsePropPath(name), value, obj, 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default formDataToJSON;
|
|
|
@ -1,111 +0,0 @@
|
||||||
import {TextEncoder} from 'util';
|
|
||||||
import {Readable} from 'stream';
|
|
||||||
import utils from "../utils.js";
|
|
||||||
import readBlob from "./readBlob.js";
|
|
||||||
|
|
||||||
const BOUNDARY_ALPHABET = utils.ALPHABET.ALPHA_DIGIT + '-_';
|
|
||||||
|
|
||||||
const textEncoder = new TextEncoder();
|
|
||||||
|
|
||||||
const CRLF = '\r\n';
|
|
||||||
const CRLF_BYTES = textEncoder.encode(CRLF);
|
|
||||||
const CRLF_BYTES_COUNT = 2;
|
|
||||||
|
|
||||||
class FormDataPart {
|
|
||||||
constructor(name, value) {
|
|
||||||
const {escapeName} = this.constructor;
|
|
||||||
const isStringValue = utils.isString(value);
|
|
||||||
|
|
||||||
let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${
|
|
||||||
!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ''
|
|
||||||
}${CRLF}`;
|
|
||||||
|
|
||||||
if (isStringValue) {
|
|
||||||
value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
|
|
||||||
} else {
|
|
||||||
headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`
|
|
||||||
}
|
|
||||||
|
|
||||||
this.headers = textEncoder.encode(headers + CRLF);
|
|
||||||
|
|
||||||
this.contentLength = isStringValue ? value.byteLength : value.size;
|
|
||||||
|
|
||||||
this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
|
|
||||||
|
|
||||||
this.name = name;
|
|
||||||
this.value = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
async *encode(){
|
|
||||||
yield this.headers;
|
|
||||||
|
|
||||||
const {value} = this;
|
|
||||||
|
|
||||||
if(utils.isTypedArray(value)) {
|
|
||||||
yield value;
|
|
||||||
} else {
|
|
||||||
yield* readBlob(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
yield CRLF_BYTES;
|
|
||||||
}
|
|
||||||
|
|
||||||
static escapeName(name) {
|
|
||||||
return String(name).replace(/[\r\n"]/g, (match) => ({
|
|
||||||
'\r' : '%0D',
|
|
||||||
'\n' : '%0A',
|
|
||||||
'"' : '%22',
|
|
||||||
}[match]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const formDataToStream = (form, headersHandler, options) => {
|
|
||||||
const {
|
|
||||||
tag = 'form-data-boundary',
|
|
||||||
size = 25,
|
|
||||||
boundary = tag + '-' + utils.generateString(size, BOUNDARY_ALPHABET)
|
|
||||||
} = options || {};
|
|
||||||
|
|
||||||
if(!utils.isFormData(form)) {
|
|
||||||
throw TypeError('FormData instance required');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (boundary.length < 1 || boundary.length > 70) {
|
|
||||||
throw Error('boundary must be 10-70 characters long')
|
|
||||||
}
|
|
||||||
|
|
||||||
const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
|
|
||||||
const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF);
|
|
||||||
let contentLength = footerBytes.byteLength;
|
|
||||||
|
|
||||||
const parts = Array.from(form.entries()).map(([name, value]) => {
|
|
||||||
const part = new FormDataPart(name, value);
|
|
||||||
contentLength += part.size;
|
|
||||||
return part;
|
|
||||||
});
|
|
||||||
|
|
||||||
contentLength += boundaryBytes.byteLength * parts.length;
|
|
||||||
|
|
||||||
contentLength = utils.toFiniteNumber(contentLength);
|
|
||||||
|
|
||||||
const computedHeaders = {
|
|
||||||
'Content-Type': `multipart/form-data; boundary=${boundary}`
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Number.isFinite(contentLength)) {
|
|
||||||
computedHeaders['Content-Length'] = contentLength;
|
|
||||||
}
|
|
||||||
|
|
||||||
headersHandler && headersHandler(computedHeaders);
|
|
||||||
|
|
||||||
return Readable.from((async function *() {
|
|
||||||
for(const part of parts) {
|
|
||||||
yield boundaryBytes;
|
|
||||||
yield* part.encode();
|
|
||||||
}
|
|
||||||
|
|
||||||
yield footerBytes;
|
|
||||||
})());
|
|
||||||
};
|
|
||||||
|
|
||||||
export default formDataToStream;
|
|
|
@ -1,53 +0,0 @@
|
||||||
'use strict';
|
|
||||||
|
|
||||||
import AxiosError from '../core/AxiosError.js';
|
|
||||||
import parseProtocol from './parseProtocol.js';
|
|
||||||
import platform from '../platform/index.js';
|
|
||||||
|
|
||||||
const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse data uri to a Buffer or Blob
|
|
||||||
*
|
|
||||||
* @param {String} uri
|
|
||||||
* @param {?Boolean} asBlob
|
|
||||||
* @param {?Object} options
|
|
||||||
* @param {?Function} options.Blob
|
|
||||||
*
|
|
||||||
* @returns {Buffer|Blob}
|
|
||||||
*/
|
|
||||||
export default function fromDataURI(uri, asBlob, options) {
|
|
||||||
const _Blob = options && options.Blob || platform.classes.Blob;
|
|
||||||
const protocol = parseProtocol(uri);
|
|
||||||
|
|
||||||
if (asBlob === undefined && _Blob) {
|
|
||||||
asBlob = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (protocol === 'data') {
|
|
||||||
uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
|
|
||||||
|
|
||||||
const match = DATA_URL_PATTERN.exec(uri);
|
|
||||||
|
|
||||||
if (!match) {
|
|
||||||
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
|
|
||||||
}
|
|
||||||
|
|
||||||
const mime = match[1];
|
|
||||||
const isBase64 = match[2];
|
|
||||||
const body = match[3];
|
|
||||||
const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
|
|
||||||
|
|
||||||
if (asBlob) {
|
|
||||||
if (!_Blob) {
|
|
||||||
throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new _Blob([buffer], {type: mime});
|
|
||||||
}
|
|
||||||
|
|
||||||
return buffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
|
|
||||||
}
|
|
|
@ -4,12 +4,11 @@
|
||||||
* Determines whether the specified URL is absolute
|
* Determines whether the specified URL is absolute
|
||||||
*
|
*
|
||||||
* @param {string} url The URL to test
|
* @param {string} url The URL to test
|
||||||
*
|
|
||||||
* @returns {boolean} True if the specified URL is absolute, otherwise false
|
* @returns {boolean} True if the specified URL is absolute, otherwise false
|
||||||
*/
|
*/
|
||||||
export default function isAbsoluteURL(url) {
|
module.exports = function isAbsoluteURL(url) {
|
||||||
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
|
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
|
||||||
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
|
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
|
||||||
// by any combination of letters, digits, plus, period, or hyphen.
|
// by any combination of letters, digits, plus, period, or hyphen.
|
||||||
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
|
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
|
||||||
}
|
};
|
||||||
|
|
|
@ -1,14 +1,11 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import utils from './../utils.js';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determines whether the payload is an error thrown by Axios
|
* Determines whether the payload is an error thrown by Axios
|
||||||
*
|
*
|
||||||
* @param {*} payload The value to test
|
* @param {*} payload The value to test
|
||||||
*
|
|
||||||
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
|
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
|
||||||
*/
|
*/
|
||||||
export default function isAxiosError(payload) {
|
module.exports = function isAxiosError(payload) {
|
||||||
return utils.isObject(payload) && (payload.isAxiosError === true);
|
return (typeof payload === 'object') && (payload.isAxiosError === true);
|
||||||
}
|
};
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue