Skip to content

3. Back end

David Kartuzinski aka Kai Dawei edited this page Apr 24, 2019 · 5 revisions

Back end

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

You can find out how to run Strapi in the Readme

Information

  • 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 Content Types:

  • Category
  • Like
  • Restaurant
  • Review

Specific customizations

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 the graphql plugin you need to ensure you update your API schema if you start adding custom behaviors within your APIs.

Here, for example, we added two fields (note and noteDetails) and a new Resolver to count the Restaurants.

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 add the note and noteDetails attributes that don't exist (at this point) in the data model of a Restaurant, we customize the controller to add it in the data response.

In the Review API we create a new service function called average. This function receives the Restaurant ID and then fetches its average Review note.

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/Restaurant.js

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

Following this line we have additional modifications that extract the correct data.

Seeding data

For this application we are using a SQLite database. This allows us to quickly create a seed script by dumping the database into a data.zip and unzipping it upon install.

Clone this wiki locally