kraph


Source link: https://github.com/taskworld/kraph

Kraph

In short, this is a GraphQL request JSON body builder for Kotlin. It will generate the JSON string for request body that work with GraphQL Server. For example, we have this GraphQL query to list all notes:

query {

  notes {

id

createdDate

content

author {

 name

 avatarUrl(size: 100)

}

  
}
 
}

Which is written in Kotlin using Kraph like this:

Kraph {

  query {

fieldObject("notes") {

 field("id")

 field("createdDate")

 field("content")

 fieldObject("author") {

  field("name")

  field("avatarUrl", mapOf("size" to 100))

 
}

}

  
}
 
}

As you can see, we can achieve our goal with just a few tweaks from the original query.

NOTE: Kraph is still in an early stage. The usage may change in further development.

Features

  • DSL builder style. Make it easier to read and use.
  • Support Cursor Connection and Input Object Mutation in Relay.

Set up

Adding Kraph to build.gradle

repositories {

  jcenter() 
}
  dependencies {

  compile "me.lazmaid.kraph:kraph:x.y.z" 
}

Guide

If you are not familiar with GraphQL syntax, it is recommended to read the GraphQL introduction for an overview of how Graphql works. Usually, you should be able to use queries from other tools (e.g. GraphiQL) with a few tweaks. First, let's see what Kraph provides for you.

Simple GraphQL

  • query and mutation represents the Query and Mutation operations of GraphQL. The name of the query or mutaton can be passed as a string.

    GraphQL:

    query GetUsers {
    
    ... 
    }
    

    Kraph:

    Kraph {
    
      query("GetUsers") {
    
    ...
      
    }
     
    }
    

    GraphQL:

    mutation UpdateUserProfile {
    
    ... 
    }
    

    Kraph:

    Kraph {
    
      mutation("UpdateUserProfile") {
    
    ...
      
    }
     
    }
    
  • field and fieldObject represent accessors for fields. Though there are technically no differences, fieldObject may be chosen for clarity to indicate that a field must contain another set of nested fields as an argument. Both of them take a Map<String, Any> that maps Kotlin data types to the GraphQL data types for input objects.

    query {
    
    users {
    
      name
      email
      avatarUrl(size: 100)
    
    }
     
    }
    
    Kraph {
    
      query {
    
    fieldObject("users") {
    
     field("name")
    
     field("email")
    
     field("avatarUrl", args = mapOf("size" to 100))
    
    }
    
      
    }
     
    }
    
  • fragment provides a mechanism for creating GraphQL Fragments. To use a fragment in a query requires two steps. The first is to define the fragment, letting Kraph know how to handle it later:

    fragment UserFragment on User {
    
    name
    email
    avatarUrl(size: 100) 
    }
    
    Kraph.defineFragment("UserFragment") {
    
      field("name")
      field("email")
      field("avatarUrl", mapOf("size" to 100)) 
    }
    

    Then, when you are creating your query, you can simply use the fragment and its fields will be expanded:

    query {
    
    users {
    
      ...UserFragment
    
    }
     
    }
    
    Kraph {
    
      query("GetUsers") {
    
    fieldObject("users") {
    
     fragment("UserFragment")
    
    }
    
      
    }
     
    }
    

Relay

  • func represents a Field inside a Mutation block that follows the Relay Input Object Mutations specification.
    mutation {
    
    userLogin(input: {
    email: "[email protected]", password: "abcd1234"
    }
    ) {
    
      accessToken
      user {
    
     id
    
     email
      
    }
    
    }
     
    }
    
    Kraph {
    
      mutation {
    
    func("userLogin", input = mapOf("email" to "[email protected]", "password" to "abcd1234")) {
    
     field("accessToken")
    
     fieldObject("user") {
    
      field("id")
    
      field("email")
    
     
    }
    
    }
    
      
    }
     
    }
    
  • cursorConnection represents a Field that follows the Relay Cursor Connections specification
    query {
    
     users(first: 10, after: "user::1234") {
    
      edges {
    
     node {
    
    id
    
    name
    
     
    }
    
      
    }
    
    }
     
    }
    
    Kraph {
    
      cursorConnection("users", first = 10, after = "user::1234") {
    
    edges {
    
     node {
    
      field("id")
    
      field("name")
    
     
    }
    
    }
    
      
    }
     
    }
    

Request/Query String

  • toRequestString() will generate a JSON body to send in POST request.
  • toGraphQueryString() will give you the formatted GraphQL string. This is very useful for debugging.
    val query = Kraph {
    
      query {
    
    fieldObject("users") {
    
     field("name")
    
     field("email")
    
     field("avatarUrl", args = mapOf("size" to 100))
    
    }
    
      
    }
     
    }
    
    println(query.toRequestString()) /*  * Result:  * {
    "query": "query {
    \nnotes {
    \nid\ncreatedDate\ncontent\nauthor {
    \nname\navatarUrl(size: 100)\n
    }
    \n
    }
    \n
    }
    ", "variables": null, "operationName": null
    }
      */ println(query.toGraphQueryString()) /*  * Result:  * query {
      *
    notes {
      *
      id  *
      createdDate  *
      content  *
      author {
      *
    
     name  *
    
     avatarUrl(size: 100)  *
      
    }
      *
    
    }
      * 
    }
      */
  • requestQueryString(), requestVariableString() and requestOperationName() provide more fine grained access to the components of the full request string, which are sometimes necessary depending on your HTTP request builder and GraphQL server setup. They provide the values for the query, variables, and operationName parameters, respectively, and so are good for creating GET requests. Please note that requestVariableString() will always return null until variable support is implemented.

Contributing to Kraph

We use Github issues for tracking bugs and requests. Any feedback and/or PRs is welcome.

Resources

A common Architecture for Android Applications developing based on MVP,integrates many Open Source Projects(like Dagger2, Rxjava, Retrofit... ), to make your developing quicker and easier.

Simple Local Broadcast(s) on top of android LocalBroadcastManager.

This is a very simple RatingBar library, which you can just simply extend BaseRatingBar to implement your own animation RatingBar in a few steps!

Feature

  • Support use touch to change rating
  • Custom drawable's padding
  • Custom your empty and filled drawable
  • Click again to clear rating
  • Rotate animation
  • Scale animation

A light-weight android library that can be quickly integrated into any app to let users choose folder, also files (but esp built for folders).

A simple customizable NumberPicker plugin for Android.

Add footer and header & item click listener to RecyclerView adapter.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes