skip to Main Content

This is the code in my background-worker.js file which is supposed to be responsible for uploading the blob

const addExerciseDataToDatabase = async (blob, exercise, patient, authToken) => {
    const databaseURL = 'http://127.0.0.1:8000/exercise_record/';

    const fileName = 'video.webm';
    const file = new File([blob], fileName, { type: blob.type });

    const formData = new FormData();
    formData.append('date', getDateWithFormat());
    formData.append('exercise', exercise);
    formData.append('patient', patient);
    formData.append('blob', file);

    const headers = new Headers({
        'Authorization': `Token ${authToken}`,
        'Content-Type':'multipart/form-data'
    });

    try {
        const response = await fetch(databaseURL, {
            method: 'POST',
            headers,
            body: formData,
        });

        if (response.ok) {
            console.log('Data Added to Database');
        } else {
            console.error('Failed to add data to the database:', response);
        }
    } catch (error) {
        console.error('Error while making the request:', error);
    }
};


// Listen for messages from the main script
this.addEventListener('message', async (event) => {
    const data = event.data;
    if (data.blob) {
        let blob = data.blob;
        console.log(blob);

        try {
            // await uploadFileFirebase(blob);
            await addExerciseDataToDatabase(blob, data.exercise, data.patient, data.authToken)

        } catch (error) {
            console.log(error);
        }
    }
});


const getDateWithFormat = () => {
    var currentDate = new Date();
    var year = currentDate.getFullYear();
    var month = String(currentDate.getMonth() + 1).padStart(2, '0');
    var day = String(currentDate.getDate()).padStart(2, '0');
    var formattedDate = year + '-' + month + '-' + day;
    return formattedDate
}

This is my model in django

class ExerciseRecord(models.Model):
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='exercise_records')
    exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='exercise_records')
    date = models.DateField()
    video = models.CharField(max_length=255, default='', null=True, blank=True)
    review = models.BooleanField(null=True, blank=True)
    commment = models.TextField(blank=True)
    blob = models.FileField(upload_to='exercise_records/', null=True, blank=True)

    def __str__(self):
        return f'{self.patient} - {self.exercise} - {self.date}'

class ExerciseRecordViewSet(viewsets.ModelViewSet):
queryset = ExerciseRecord.objects.all()
serializer_class = ExerciseRecordSerializer

def get_queryset(self):
    if hasattr(self.request.user, "patient"):
        return ExerciseRecord.objects.filter(patient__user=self.request.user)
    elif hasattr(self.request.user, "fittlyf_physio"):
        patient_id = self.request.query_params.get("patient_id")
        exercise_record_id = self.request.query_params.get("exercise_record_id")

        if patient_id:
            return ExerciseRecord.objects.filter(patient__id=patient_id)
        if exercise_record_id:
            return ExerciseRecord.objects.filter(id=exercise_record_id)

def perform_create(self, request, *args, **kwargs):
    print(request.data)

    patient_exercises_ids = [
        patient_exercise.exercise.id
        for patient_exercise in PatientExercise.objects.filter(
            patient=request.data["patient"]
        )
    ]

    today_completed_exercise_ids = [
        exercise_record.exercise.id
        for exercise_record in ExerciseRecord.objects.filter(
            date=request.data["date"], patient=request.data["patient"]
        )
    ]

    completed_all_exercises = set(patient_exercises_ids) == set(
        today_completed_exercise_ids
    )
    if completed_all_exercises:
        patient_id = request.data["patient"]
        patient = Patient.objects.get(pk=patient_id)
        patient.completed_exercise_date = date.today()
        patient.save()

    serializer = ExerciseRecordSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The response that I receive in terminal:-

Bad Request: /exercise_record/
[13/Oct/2023 10:02:54] "POST /exercise_record/ HTTP/1.1" 400 77

Blob {size: 64688, type: ‘video/webm;codecs=vp8’}

this is how the blob looks in console

background-worker.js:51 Failed to add data to the database: Response {type: 'cors', url: 'http://127.0.0.1:8000/exercise_record/', redirected: false, status: 400, ok: false, …}
addExerciseDataToDatabase @ background-worker.js:51
await in addExerciseDataToDatabase (async)
(anonymous) @ background-worker.js:67

I get some this kind of response

Please help me with this and let me know what am I doing wrong, Everything is correct in the backend I am sure about that as rest endpoints responsible for file uploading works but not this one

When I remove the content-type from the headers this is what I get at print(request.data) at the viewset. Everything thing works fine except that the blob is empty

{'date': '2023-10-13', 'video': None, 'review': False, 'blob': None, 'patient': 80, 'exercise': 12}

2

Answers


  1. Chosen as BEST ANSWER

    Don't know why but when I commented the def perform_create() function then everything works, there is something in that function with makes the blob vanish.


  2. I see that your backend endpoint in this code is also local, so if you set the django DEBUG=True in your local settings file, you probably can get a better hint about what’s going on from your Django stdout/logs.

    Could it be the same problem that is mentioned in this question?

    Also I think it would be helpful if you also share the ExerciseRecordSerializer in your question as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search