Skip to content

3. Back end

Jim LAURIE edited this page Apr 24, 2019 · 5 revisions

Back end

Food Advisor's back-end is build with Strapi.

You can find how to run it in the Readme

Informations

  • Strapi version: 3.0.0-alpha.24.1
  • Database: SQLite

Features we are using

APIs

We are using Strapi's capacity to bootstrap APIs quickly:

We built the following APIs:

  • Category
  • Like
  • Restaurant
  • Review

Specific developments

GraphQL

Food Advisor's front-end is built using React and GraphQL so we decided to use the graphql plugin.

📚 Plugin documentation here.

When using graphql plugin you need to make sure you update your API schema if you start adding custom behaviours in your APIs.

Here for example, We added two fields (note and noteDetails) and a new resolver to count the restaurant.

Path - ./api/restaurant/config/schema.graphql.js

module.exports = {
  definition: /* GraphQL */ `
    extend type Restaurant {
      note: Float
      noteDetails: [RestaurantNote!]!
    }

    type RestaurantsConnection {
      aggregate: RestaurantsAggregate
    }

    type RestaurantsAggregate {
      count: Int
    }


    type RestaurantNote {
      note: Int
      count: Int
    }
  `,
  query: /* GraphQL */ `
    restaurantsConnection(where: JSON): RestaurantsConnection
  `,
  resolver: {
    Query: {
      restaurantsConnection(_, args) {
        return args;
      }
    },
    RestaurantsConnection: {
      aggregate(args) {
        return args;
      }
    },
    RestaurantsAggregate: {
      count(args) {
        return strapi.controllers.restaurant.count({
          query: args.where || {}
        });
      }
    }
  }
};

📚Custom schema documentation here.

REST

To create the note and noteDetails attributes that doesn't exist in the data model of a restaurant we customized the controller to add it in the data response.

In the review API we create a new service function named average. This function receive the restaurant ID and fetch the average of review's note that match with the restaurant we want.

Path - ./api/review/services/Review.js

return Review.query(function(qb) {
  qb.avg('note');
  qb.where('restaurant', '=', restaurant);
}).fetch();

Here we use the knex query function available in the Global variable of the model.

Then to apply it in the response data we call the service function in the restaurant API controller findOne function.

Path - ./api/restaurant/services/Restaurat.js

let note = await strapi.api.review.services.review.average(restaurant.id);

Then we apply some modification to extract the correct data.

Seeding data

For this app we are using a sqlite database. This allowed us to quickly create a seed script by dumping the database into a data.zip and uncompressing it on install to provide data as soon as the app is installed.

Clone this wiki locally