sanger/sequencescape

View on GitHub
lib/tasks/jsorm.rake

Summary

Maintainability
Test Coverage
F
11%
# frozen_string_literal: true

namespace :jsorm do
  desc 'Spits out a js configuration'
  task create_config: :environment do
    puts <<~HEREDOC
      /*
       * Autogenerated by sequencescape on #{Time.zone.now}"
       * bundle exec rake jsorm:create_config"
       *
       * Generates a Sequencescape API object
       * Needs to be initialized with the root URL
       * Usage example:
       *
       * import ApiModule from 'shared/api'
       * const Api = ApiModule(baseUrl: 'http://sequencescape.url/port')
       * var plate = Api.Plate.find('1')
       */
       const {
        JSORMBase,
        attr,
        belongsTo,
        hasMany
        // etc
      } = require('jsorm/dist/jsorm')
       const Api = function (options) {
         const ApplicationRecord = JSORMBase.extend({
          static: {
            baseUrl: options.baseUrl || 'http://localhost:3000',
            apiNamespace: options.apiNamespace || '/api/v1'
          }
        })
         return {
    HEREDOC

    Api::V2.constants.each do |resource_key|
      resource = Api::V2.const_get(resource_key)
      next unless resource < Api::V2::BaseResource

      name = resource_key.to_s.gsub('Resource', '')
      type = resource._type
      puts "    #{name}: ApplicationRecord.extend({"
      puts "      static: { jsonapiType: '#{type}' },"
      puts '      attrs: {'
      resource._attributes.each_key do |attr|
        jsoncase = attr.to_s.split('_').reduce { |attribute, word| attribute << word.upcase_first }
        puts "        #{jsoncase}: attr(),"
      end
      resource._relationships.each do |attr, details|
        jsoncase = attr.to_s.split('_').reduce { |attribute, word| attribute << word.upcase_first }
        relation = details.is_a?(JSONAPI::Relationship::ToOne) ? 'belongsTo' : 'hasMany'
        puts "        #{jsoncase}: #{relation}(),"
      end
      puts '      },'
      puts '      methods: {}'
      puts '    }),'
    end
    puts '  }'
    puts '}'
    puts ''
    puts 'export default Api'
  end
end