Thursday, October 13, 2016

Add Base URLs to Grails Page and Scripts

Sometimes we are note sure about final deployment context root address, so the root of the application can be something like mydomain.com/ or mydomain/myapp/ .

Grails or most of the other web app frameworks handle the link creation for such situation with some link facility in pages, but the problem is links in JavaScript, like base url for ajax call or resource loaders.

One possible solution is finding the base urls using the same facility of the framework and set them in global javascript variables.

The best location to add them and complying DRY is the layout page, where all pages have access.

The following is a sample for grails framework to have the url of the root of the app and the assets as well.


window.grails = {
    baseUrl: '${raw(g.createLink(absolute:true, uri:"/"))}'
    assetsUrl : '${ raw(asset.assetPath(src: '')) }',
};


It can be used like this:

$.ajax({
    type: 'GET',
    url: window.grails.baseUrl + 'controller/show/' + id +'.json',
    contentType: 'application/json',
    success: function( data, textStatus, jqXHR )
    {
    },
    error: function( jqXHR, textStatus, errorThrown )
    {
    }
});

First Swagger

Start by editing sample or own simple one

http://editor.swagger.io/

Generate client or server code online in editor or get more customizable package by online generator

curl -X POST -H "content-type:application/json" -d '{"options": {"packageName": "rira_api"},"swaggerUrl":"https://raw.githubusercontent.com/omidmt/rira/0.7.x/api/swagger-api.yaml"}' http://generator.swagger.io/api/gen/clients/python

Response:

{"code":"55b0eb81-87ba-48ff-91f5-3a4444a95462","link":"https://generator.swagger.io/api/gen/download/55b0eb81-87ba-48ff-91f5-3a4444a95462

Sample security definition by 2 ways of using it for client (query/header)

securityDefinitions:
  apikeyHeader:
    type: apiKey
    name: apiKey
    in: header
  apikeyQuery:
    type: apiKey
    name: apiKey
    in: query
security:
  - apikeyHeader: []
  - apikeyQuery: []

[] means apply to all operations, but different definition can be applied per path/operation as well.

Enabe debug mode:
rira_api.configuration.debug = True