Implement Method To Update A User Profile

by ADMIN 42 views

Overview

In this article, we will discuss the implementation of a method to update a user profile. This method will allow an unauthenticated user to update information about their own profile, including their first name, last name, and profile picture. We will also cover the process of deleting the old profile picture from an AWS bucket when a new one is uploaded.

Requirements

Before we begin, let's outline the requirements for this method:

  • The user should be able to update their first name.
  • The user should be able to update their last name.
  • The user should be able to update their profile picture.
  • If the user updates their profile picture, the old picture should be deleted from the AWS bucket.

Database Schema

To implement this method, we will need a database schema that includes the necessary fields for a user profile. Here is an example of what the schema might look like:

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  first_name VARCHAR(255) NOT NULL,
  last_name VARCHAR(255) NOT NULL,
  profile_picture VARCHAR(255) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Backend Implementation

We will implement this method using a Node.js backend with Express.js. We will use the multer middleware to handle file uploads and the aws-sdk library to interact with the AWS bucket.

Step 1: Set up the Backend

First, we need to set up our backend using Express.js. We will create a new file called server.js and add the following code:

const express = require('express');
const app = express();
const multer = require('multer');
const AWS = require('aws-sdk');

// Set up AWS bucket
const s3 = new AWS.S3({
  accessKeyId: 'YOUR_ACCESS_KEY_ID',
  secretAccessKey: 'YOUR_SECRET_ACCESS_KEY',
  region: 'YOUR_REGION'
});

// Set up multer
const upload = multer({
  dest: './uploads/',
  limits: { fileSize: 1000000 },
  fileFilter(req, file, cb) {
    if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
      return cb(new Error('Only image files are allowed!'));
    }
    cb(null, true);
  }
});

// Set up routes
app.post('/update-profile', upload.single('profile_picture'), (req, res) => {
  // Update user profile
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Step 2: Update User Profile

Next, we need to update the user profile. We will create a new function called updateUserProfile that will handle this logic. We will add the following code to the server.js file:

const db = require('./db');

// Update user profile
async function updateUserProfile(req, res) {
  try {
    const userId = req.user.id;
    const firstName = req.body.firstName;
    const lastName = req.body.lastName;
    const profilePicture = req.file.filename;

    // Update user profile in database
    const updatedUser = await db.query(`UPDATE users SET_name = $1, last_name = $2, profile_picture = $3 WHERE id = $4 RETURNING *`, [firstName, lastName, profilePicture, userId]);

    // Delete old profile picture from AWS bucket
    if (updatedUser.rows[0].profile_picture) {
      const params = {
        Bucket: 'YOUR_BUCKET_NAME',
        Key: updatedUser.rows[0].profile_picture
      };
      s3.deleteObject(params, (err, data) => {
        if (err) {
          console.log(err);
        } else {
          console.log(data);
        }
      });
    }

    res.json({ message: 'User profile updated successfully' });
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: 'Error updating user profile' });
  }
}

Step 3: Handle File Upload

Finally, we need to handle the file upload. We will create a new function called handleFileUpload that will handle this logic. We will add the following code to the server.js file:

// Handle file upload
async function handleFileUpload(req, res) {
  try {
    const file = req.file;
    const userId = req.user.id;

    // Upload file to AWS bucket
    const params = {
      Bucket: 'YOUR_BUCKET_NAME',
      Key: file.filename,
      Body: file.buffer
    };
    s3.upload(params, (err, data) => {
      if (err) {
        console.log(err);
      } else {
        console.log(data);
      }
    });

    res.json({ message: 'File uploaded successfully' });
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: 'Error uploading file' });
  }
}

Frontend Implementation

We will implement the frontend using React.js. We will create a new file called App.js and add the following code:

import React, { useState } from 'react';
import axios from 'axios';

function App() {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [profilePicture, setProfilePicture] = useState(null);

  const handleUpdateProfile = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('firstName', firstName);
    formData.append('lastName', lastName);
    formData.append('profile_picture', profilePicture);

    try {
      const response = await axios.post('/update-profile', formData);
      console.log(response.data);
    } catch (err) {
      console.log(err);
    }
  };

  const handleFileChange = (e) => {
    setProfilePicture(e.target.files[0]);
  };

  return (
    <div>
      <form onSubmit={handleUpdateProfile}>
        <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} placeholder="First Name" />
        <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} placeholder="Last Name" />
        <input type="file" onChange={handleFileChange} />
        <button type="submit">Update Profile</button>
      </form>
    </div>
  );
}

export default App;

Conclusion

Frequently Asked Questions

In this article, we will answer some frequently asked questions about implementing a method to update a user profile.

Q: What are the requirements for this method?

A: The requirements for this method are:

  • The user should be able to update their first name.
  • The user should be able to update their last name.
  • The user should be able to update their profile picture.
  • If the user updates their profile picture, the old picture should be deleted from the AWS bucket.

Q: What is the database schema for this method?

A: The database schema for this method is:

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  first_name VARCHAR(255) NOT NULL,
  last_name VARCHAR(255) NOT NULL,
  profile_picture VARCHAR(255) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Q: How do I implement the backend for this method?

A: To implement the backend for this method, you will need to use a Node.js framework such as Express.js. You will also need to use the multer middleware to handle file uploads and the aws-sdk library to interact with the AWS bucket.

Here is an example of how you might implement the backend:

const express = require('express');
const app = express();
const multer = require('multer');
const AWS = require('aws-sdk');

// Set up AWS bucket
const s3 = new AWS.S3({
  accessKeyId: 'YOUR_ACCESS_KEY_ID',
  secretAccessKey: 'YOUR_SECRET_ACCESS_KEY',
  region: 'YOUR_REGION'
});

// Set up multer
const upload = multer({
  dest: './uploads/',
  limits: { fileSize: 1000000 },
  fileFilter(req, file, cb) {
    if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
      return cb(new Error('Only image files are allowed!'));
    }
    cb(null, true);
  }
});

// Set up routes
app.post('/update-profile', upload.single('profile_picture'), (req, res) => {
  // Update user profile
});

Q: How do I handle file uploads for this method?

A: To handle file uploads for this method, you will need to use the multer middleware to handle the file upload. You will also need to use the aws-sdk library to upload the file to the AWS bucket.

Here is an example of how you might handle file uploads:

// Handle file upload
async function handleFileUpload(req, res) {
  try {
    const file = req.file;
    const userId = req.user.id;

    // Upload file to AWS bucket
    const params = {
      Bucket: 'YOUR_BUCKET_NAME',
      Key: file.filename,
      Body: file.buffer
    };
    s3.upload(params, (err, data) => {
      if (err) {
        console.log(err);
      } else {
        console.log(data);
      }
    });

    res.json({ message: 'File uploaded successfully' });
  } catch (err) {
    console.log(err    res.status(500).json({ message: 'Error uploading file' });
  }
}

Q: How do I delete the old profile picture from the AWS bucket when a new one is uploaded?

A: To delete the old profile picture from the AWS bucket when a new one is uploaded, you will need to use the aws-sdk library to delete the old file from the bucket.

Here is an example of how you might delete the old profile picture:

// Delete old profile picture from AWS bucket
if (updatedUser.rows[0].profile_picture) {
  const params = {
    Bucket: 'YOUR_BUCKET_NAME',
    Key: updatedUser.rows[0].profile_picture
  };
  s3.deleteObject(params, (err, data) => {
    if (err) {
      console.log(err);
    } else {
      console.log(data);
    }
  });
}

Q: How do I implement the frontend for this method?

A: To implement the frontend for this method, you will need to use a JavaScript framework such as React.js. You will also need to use the axios library to make requests to the backend.

Here is an example of how you might implement the frontend:

import React, { useState } from 'react';
import axios from 'axios';

function App() {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [profilePicture, setProfilePicture] = useState(null);

  const handleUpdateProfile = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('firstName', firstName);
    formData.append('lastName', lastName);
    formData.append('profile_picture', profilePicture);

    try {
      const response = await axios.post('/update-profile', formData);
      console.log(response.data);
    } catch (err) {
      console.log(err);
    }
  };

  const handleFileChange = (e) => {
    setProfilePicture(e.target.files[0]);
  };

  return (
    <div>
      <form onSubmit={handleUpdateProfile}>
        <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} placeholder="First Name" />
        <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} placeholder="Last Name" />
        <input type="file" onChange={handleFileChange} />
        <button type="submit">Update Profile</button>
      </form>
    </div>
  );
}

export default App;

Conclusion

In this article, we answered some frequently asked questions about implementing a method to update a user profile. We covered the requirements, database schema, backend implementation, and frontend implementation. We also covered the process of deleting the old profile picture from the AWS bucket when a new one is uploaded.