npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dinevillar/adonis-json-api-serializer

v0.5.7

Published

AdonisJS Agnostic JSON Rest Api Specification Wrapper

Downloads

6

Readme

Installation

npm i @dinevillar/adonis-json-api-serializer

Setup

Create/edit config/jsonApi.js.

module.exports = {
      "globalOptions": {
          "convertCase": "snake_case",
          "unconvertCase": "camelCase"
      },
      // Register JSON API Types here..
      "registry": {
          "user": {
              "model": 'App/Models/User'
              "structure": {
                  "links": {
                      self: (data) => {
                          return '/users/' + data.id
                      }
                  },
                  "topLevelLinks": {
                      self: '/users'
                  }
              }
          }
      }
  };

Add as provider (start/app.js)

const providers = [
	'@dinevillar/adonis-json-api-serializer/providers/JsonApiProvider'
]

Add to your Models

static get Serializer() {
    return 'JsonApi/Serializer/LucidSerializer'; // Override Lucid/VanillaSerializer
};

Add as named Middleware in start/kernel.js

const namedMiddleware = {
  jsonApi: 'JsonApi/Middleware/Specification'
};

Use in your routes

// All request and response to /user must conform to JSON API v1
Route.resource('user', 'UserController')
    .middleware(['auth', 'jsonApi'])

You can use the "cn" and "ro" schemes of the middleware.

  • Adding "cn" (jsonApi:cn) will allow middleware to check for Content Negotiation
  • Adding "ro" (jsonApi:ro) will allow middleware to check if request body for POST and PATCH conforms with JSON API resource object rules
  • Adding "ro" (jsonApi:ro) also will automatically deserialize resource objects.
  • If none is specified then both will be applied

Usage

model.toJSON():

getUser({request, response}) {
  const user = await User.find(1);
  response.send(user.toJSON());
};

with relations:

config/jsonApi.js

"registry": {
	"company": {
	    "model": 'App/Models/Company',
	    "structure": {
            id: "id",
            links: {
                self: (data) => {
                  return '/companies/' + data.id
                }
            }
		}
	}
	"user": {
	    "model": 'App/Models/User',
	    "structure": {
            "links": {
                self: (data) => {
                    return '/users/' + data.id
                }
            },
            "relationships": {
                company: {
                  type: 'company',
                  links: {
                    self: '/companies'
                  }
                }
            }
            "topLevelLinks": {
                self: '/users'
            }
		}
  	}
 }

App/Models/Company

static get Serializer() {
    return 'JsonApi/Serializer/LucidSerializer';
};

App/Models/User

static get Serializer() {
    return 'JsonApi/Serializer/LucidSerializer';
};

Somewhere:

getUser({request, response}) {
  const user = await User.find(1);
  await user.load('company'); // load relation
  response.send(user.toJSON());
};

Record Browser in your Controllers

const Company = use('App/Models/Company')
const JsonApiRB = use('JsonApiRecordBrowser');
const companies = await JsonApiRB
  .model(Company)
  .request(request.get()) //handle request
  .paginateOrFetch();
response.send(companies.toJSON());

The record browser supports:

Exceptions

You can use JsonApi to handle errors and be able to return valid JSON Api error responses. Create a global ehandler using adonis make:ehandler and use JsonApi in handle() function. See examples/Exception/Handler.js

async handle(error, options) {
    JsonApi.handleError(error, options);
}

Validator

Sample Validator (see examples)

const {formatters} = use('Validator');
const JsonApi = use('JsonApi');
class UserValidator {
    get rules(){
        return {
            'username': 'required|accepted|max:255',
            'contact_number': 'required|accepted|max:50',
            'email': 'required|email|unique:companies,email|max:100'
        }
    }
    
    get formatter() {
        return formatters.JsonApi;
    }
    
    async fails({errors}) {
        for (const error of errors) {
            const jsonError = JsonApi.JSE.UnprocessableResourceObject.invoke();
            jsonError.detail = error.detail;
            jsonError.source = error.source;
            JsonApi.pushError(jsonError);
        }
        return this.ctx.response
            .status(JsonApi.getJsonErrorStatus())
            .send(JsonApi.getJsonError());
    }
}

Serializer Library:

Serializer functions

const {JsonApiSerializer} = use('JsonApi');
const user = await User.find(1);
JsonApiSerializer.serialize("user", user);