اذهب إلى المحتوى
  • 0

redis

Aimen Zeffanine

السؤال

السلام عليكم
احاول استخدام redis من اجل تحسين الاداء و لكن لم اعرف كبف ارجو المساعدة

const models = require('../models');
const fs = require('fs/promises');
const Redis = require('redis');

const client = Redis.createClient({
    password: 'QMzeBdscHuO1zEUGT1iaYsm747yaHJAa',
    socket: {
        host: 'redis-16975.c135.eu-central-1-1.ec2.cloud.redislabs.com',
        port: 16975
    }
});

client.on('error', err => console.log('Redis Client Error', err));


exports.newPost = async (req, res) => {
    const {title, contents, steps, country, region} = req.body;
    try {
        const post = await models.Post.create({
            title,
            contents,
            steps,
            country,
            region,
            UserId: req.currentUser.id
        });
        req.files.map(async function(file) {
            const post_img = await models.Post_Image.create({
                img_uri: '/public/images/' + file.filename,
                PostId: post.id
            })
        })
        res.status(200).json({message: "تم إضافة منشور جديد"})
    } catch(e) {
        res.status(500).json(e)
    }
}

exports.getAllPosts = async (req, res) => {
    try {

        await client.connect();

        const redisKey = 'all_posts';
        // Check if the data exists in Redis cache
        client.get(redisKey, async (err, cachedPosts) => {
            if (err) {
                console.error('Error retrieving data from Redis cache:', err);
            }
            if (cachedPosts) {
                // Data exists in cache, return it
                console.log('Data found in Redis cache');
                res.status(200).json(JSON.parse(cachedPosts));
            } else {
                // Data doesn't exist in cache, retrieve from the database
                const getPosts = await models.Post.findAll({
                    include: [
                        {
                            model: models.User,
                            attributes: { exclude: ['password', 'email'] }
                        },
                        {
                            model: models.Post_Image
                        }
                    ]
                });
                // Store the data in Redis cache
                client.set(redisKey, JSON.stringify(getPosts), (err, reply) => {
                    if (err) {
                        console.error('Error storing data in Redis cache:', err);
                    }
                    console.log('Data stored in Redis cache');
                });
                res.status(200).json(getPosts);
            }
        });
    } catch (e) {
        console.error('Error retrieving posts:', e);
        res.status(500).json(e);
    }
}


exports.getPost = async (req, res) => {
    try {
        const post = await models.Post.findOne({
            where: {id: req.params.postId},
            include: [
                {
                    model: models.User,
                    attributes: {exclude: ['password', 'email']}
                },
                {
                    model: models.Post_Image
                }
            ]
        });
        res.status(200).json(post)
    } catch(e) {
        res.status(500).json(e)
    }
}

exports.getMyAllPosts = async (req, res) => {
    try{
        const myPosts = await models.Post.findAll({
            where: {UserId: req.currentUser.id},
            include: [
                {
                    model: models.Post_Image
                }
            ]
        });
        res.status(200).json(myPosts)
    } catch(e) {
        res.status(500).json(e)
    }
}

exports.getMyPost = async (req, res) => {
    try {
        const myPost = await models.Post.findOne({
            where: {
                UserId: req.currentUser.id,
                id: req.params.postId
            }
        });
        res.status(200).json(myPost)
    } catch(e) {
        res.status(500).json(e)
    }
}

exports.updateMyPost = async (req, res) => {
    const {title, contents, steps} = req.body;
    try {
        const updatePost = await models.Post.update(
            {
                title,
                contents,
                steps
            },
            {
                where: {
                    id: req.params.postId,
                    UserId: req.currentUser.id
                }
            }
        );
        res.status(200).json({
            message: "تم التعديل على بيانات المنشور"
        })
    } catch(e) {
        res.status(500).json(e)
    }
}

exports.deleteMyPost = async (req, res) => {
    const {postId} = req.body;
    try {
        await models.Post_Image.findAll({
            where: {PostId: postId}
        }).then(res => {
            res.map((img) => {
                fs.unlink('.' + img.img_uri, function(err) {
                    if (err) throw err
                })
            })
        })
        await models.Post_Image.destroy({
            where: {PostId: postId}
        });
        await models.Comment.destroy({
            where: {PostId: postId}
        });
        await models.Like.destroy({
            where: {PostId: postId}
        });
        await models.Post.destroy({
            where: {id: postId, UserId: req.currentUser.id}
        })
        res.status(200).json({message: "تم حذف منشورك"})
    } catch(e) {
        res.status(500).json(e)
    }
}

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

 

Redis : هو نظام قاعدة بيانات يستخدم لتخزين واسترجاع البيانات بسرعة عالية. يتميز Redis بكونه سريعًا ، ويدعم العديد من البيانات الأساسية مثل السلاسل (Strings) والقوائم (Lists) والمجموعات (Sets) والمخطوطات (Hashes) والترتيبات المرتبطة بالنصوص (Sorted Sets)، بالإضافة إلى دعم توسيع الوظائف بواسطة مكتبات مضمنة.

دعنا نطبق علي كيفية استخدام Redis في الداله الخاصه بك getMyAllPosts

اولا قم بتثبيت المكتبه عن طريق هذه الامر 

npm install redis

ثانيا يجب عليك استرداد المكتبه بهذه الطريقه
 

const Redis = require('redis');

ثالثا يجب عليك انشاء اتصال بالخادم

const redisClient = Redis.createClient();

ثما يمكنك استخدام  Redis مع دالة getMyAllPosts لستصبح بهذه الشكل 
 

exports.getMyAllPosts = async (req, res) => {
    try {
        // التحقق مما إذا كانت البيانات موجودة في ذاكرة Redis
        redisClient.get('myAllPosts', async (err, cachedPosts) => {
            if (err) {
                console.error('Error retrieving data from Redis cache:', err);
            }
            if (cachedPosts) {
                // إذا تم العثور على البيانات في ذاكرة Redis، استرجاعها وإرجاعها كاستجابة
                console.log('Data found in Redis cache');
                res.status(200).json(JSON.parse(cachedPosts));
            } else {
                // إذا لم يتم العثور على البيانات في ذاكرة Redis، قم بالاستعلام عن قاعدة البيانات وتخزين النتائج في ذاكرة Redis
                const myPosts = await models.Post.findAll({
                    where: {UserId: req.currentUser.id},
                    include: [
                        {
                            model: models.Post_Image
                        }
                    ]
                });

                // تخزين البيانات في ذاكرة Redis للاستفادة منها في الطلبات المستقبلية
                redisClient.set('myAllPosts', JSON.stringify(myPosts), (err, reply) => {
                    if (err) {
                        console.error('Error storing data in Redis cache:', err);
                    }
                    console.log('Data stored in Redis cache');
                });

                // إرجاع البيانات كاستجابة
                res.status(200).json(myPosts);
            }
        });
    } catch (e) {
        console.error('Error retrieving posts:', e);
        res.status(500).json(e);
    }
}


 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0
بتاريخ On 3‏/4‏/2024 at 07:25 قال Taha Khalid:

 

Redis : هو نظام قاعدة بيانات يستخدم لتخزين واسترجاع البيانات بسرعة عالية. يتميز Redis بكونه سريعًا ، ويدعم العديد من البيانات الأساسية مثل السلاسل (Strings) والقوائم (Lists) والمجموعات (Sets) والمخطوطات (Hashes) والترتيبات المرتبطة بالنصوص (Sorted Sets)، بالإضافة إلى دعم توسيع الوظائف بواسطة مكتبات مضمنة.

دعنا نطبق علي كيفية استخدام Redis في الداله الخاصه بك getMyAllPosts

اولا قم بتثبيت المكتبه عن طريق هذه الامر 

npm install redis

ثانيا يجب عليك استرداد المكتبه بهذه الطريقه
 

const Redis = require('redis');

ثالثا يجب عليك انشاء اتصال بالخادم

const redisClient = Redis.createClient();

ثما يمكنك استخدام  Redis مع دالة getMyAllPosts لستصبح بهذه الشكل 
 

exports.getMyAllPosts = async (req, res) => {
    try {
        // التحقق مما إذا كانت البيانات موجودة في ذاكرة Redis
        redisClient.get('myAllPosts', async (err, cachedPosts) => {
            if (err) {
                console.error('Error retrieving data from Redis cache:', err);
            }
            if (cachedPosts) {
                // إذا تم العثور على البيانات في ذاكرة Redis، استرجاعها وإرجاعها كاستجابة
                console.log('Data found in Redis cache');
                res.status(200).json(JSON.parse(cachedPosts));
            } else {
                // إذا لم يتم العثور على البيانات في ذاكرة Redis، قم بالاستعلام عن قاعدة البيانات وتخزين النتائج في ذاكرة Redis
                const myPosts = await models.Post.findAll({
                    where: {UserId: req.currentUser.id},
                    include: [
                        {
                            model: models.Post_Image
                        }
                    ]
                });

                // تخزين البيانات في ذاكرة Redis للاستفادة منها في الطلبات المستقبلية
                redisClient.set('myAllPosts', JSON.stringify(myPosts), (err, reply) => {
                    if (err) {
                        console.error('Error storing data in Redis cache:', err);
                    }
                    console.log('Data stored in Redis cache');
                });

                // إرجاع البيانات كاستجابة
                res.status(200).json(myPosts);
            }
        });
    } catch (e) {
        console.error('Error retrieving posts:', e);
        res.status(500).json(e);
    }
}


 

لم اعرف كيف ارجو المساعدة 

backend.rar

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...