Thursday, 30 November, 2017 UTC


Summary

Recently, I had the need to share an svg chart between a javascript (React) app, an android app, and an iOS app. One option would be to write code in all three application to generate the chart, but a better option is to push the generation of the chart to our Swagger Express Server.
The chart I created only had a couple dozen data points on it, but its easy to imagine a case were we had many hundreds of points that we would want to use the server to generate. Moving your svg to the server also gives you the ability to use server caching, and insulate you from the limitations of your user’s machine.

Swagger yaml

First we need to setup swagger to return our image
swagger: "2.0"
info:
  version: "0.0.1"
  title: SVG App
host: localhost:10010
basePath: /
schemes:
  - http
  - https
consumes:
  - application/json
produces:
  - image/svg+xml
paths:
  /svg:
    x-swagger-router-controller: svg
    get:
      operationId: chart
      summary: Get the logo image
      responses:
        "200":
          description: Success
          schema:
            type: file
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
  /swagger:
    x-swagger-pipe: swagger_raw
definitions:
  ErrorResponse:
    required:
      - message
    properties:
      message:
        type: string

Controller

Next we need to setup our controller to return the correct content-type and call our service to build the chart.
'use strict';
 
const chartService = require('../services/chartService')
 
module.exports = {
  chart: chart
}
 
function chart (req, res) {
 
  res.setHeader('content-type', 'image/svg+xml')
 
  res.status(200).send(chartService.buildChart())
 
}

Service

Finally, let’s build our svg in our ChartService. In this simple example, its just a red circle, but here you could use a library like d3-node to create something more powerful.
Build svg in service
'use strict'
 
module.exports = {
  buildChart: buildChart
}
 
function buildChart(){
 
  const chart = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />Sorry, your browser does not support inline SVG. </svg>'
 
  return chart
 
}
Check out the whole example project.