Implementing Sponsors API for Events and Using Image Upload Widget in Open Event Frontend

 

This blog article will talk about how sponsors API has been implemented in events edit dashboard of Open Event Frontend. This discussion involves the /events/{event_identifier}/edit/sponsors route. Primary API endpoint of Open Event Server for fetching sponsors of an event are

GET         /v1/events/{event_identifier}/sponsors{?sort,filter}

GET        /v1/sponsors/{sponsor_id}

Next, we define the corresponding models according to the type of response returned by the server. This model extends the Base model.

import attr from 'ember-data/attr';
import ModelBase from 'open-event-frontend/models/base';
import { belongsTo } from 'ember-data/relationships';
import { computedSegmentedLink } from 'open-event-frontend/utils/computed-helpers';

export default ModelBase.extend({
 name        : attr('string'),
 level       : attr('number'),
 type        : attr('string'),
 url         : attr('string'),
 description : attr('string'),
 logoUrl     : attr('string'),

 event: belongsTo('event'),

 segmentedLink: computedSegmentedLink.bind(this)('url')
});

 

Here all the field attributes clearly signify what they mean. Event field has a relationship to events model, hence it is bound to event model through

belongsTo( ).

Next we fetch the data from the API and feed it into sponsor edit form available at event/{event_identifier}/edit/sponsor .

import Route from '@ember/routing/route';
import EventWizardMixin from 'open-event-frontend/mixins/event-wizard';

export default Route.extend(EventWizardMixin, {
 titleToken() {
   return this.get('l10n').t('Sponsors');
 },
 async model() {
   let data = this.modelFor('events.view.edit');
   data.sponsors = await data.event.get('sponsors');
   return data;
 }
});

 

We have defined model() asynchronously and return the fetched data to template. This data passes into sponsor form of event wizard located here.

We see that this form contains many widgets for handling form validation and its structure. Here we will explore the image upload widget of open event frontend that helps us adding image upload option to many forms across open event frontend.

Image upload component is like any other component of ember with many functions. This widget mainly includes processFiles() and uploadFiles(). Let us look at their working one by one. Full code of image-upload.js can be seen here.

processFiles(files) {
   if (files && files[0]) {
     isFileValid(files[0], this.maxSizeInKb, ['image/jpeg', 'image/png']).then(() => {
       const reader = new FileReader();
       reader.onload = e => {
         const untouchedImageData = e.target.result;
         if (this.get('needsCropper')) {
           this.set('imgData', untouchedImageData);
           this.set('cropperModalIsShown', true);
         } else {
           this.uploadImage(untouchedImageData);
         }
       };
       reader.readAsDataURL(files[0]);

     }).catch(error => {
       this.notify.error(error);
     });
   } else {
     this.notify.error(this.get('l10n').t('No FileReader support. Please use a more latest browser'));
   }

 },

 

This function accepts file input and processes them. It first passes it to a isFileValid() function with all arguments, which returns true if the files are in correct format. It then checks the dimensions and figures out if the image needs a cropper for cropping image. If yes, it opens a cropper modal and lets user crop the image to perfect size.

It then calls uploadImage() function to upload the cropped image. UploadImage() function looks something like this:

uploadImage(imageData) {
   this.set('selectedImage', imageData);
   this.set('needsConfirmation', false);
   this.set('uploadingImage', true);
   this.get('loader')
     .post('/upload/image', {
       data: imageData
     })
     .then(image => {
       this.set('uploadingImage', false);
       this.set('imageUrl', image.url);
     })
     .catch(() => {
       this.set('uploadingImage', false);
       this.set('errorMessage', this.i18n.t('An unexpected error occurred.'));
     });
 },

 

This function on receiving image data send a post request to the server for uploading the image to requested directory. If the server does not behave properly then it exits with an error.

Widgets such as image-upload help us to maintain our code in a better way by allowing re-usability of code. Ember provides good support for such controller, adapters, widgets to be used in the app.

Resources:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.