Fortune JSON API Serializer

2.3.1 · active · verified Wed Apr 22

This package functions as a robust JSON API serializer specifically designed for Fortune.js. It meticulously implements all features outlined in the JSON API specification (jsonapi.org) and adheres closely to its recommendations. The current stable version is 2.3.1. While there isn't a fixed release schedule, updates are typically driven by dependency upgrades, bug fixes, and occasional feature additions, as observed in recent minor bumps. Its core differentiators include deep integration with the Fortune.js data abstraction layer, ensuring consistent and compliant JSON API data formatting, and extensive configurability through an `options` object. This allows developers to fine-tune aspects like URL prefixes, field and type inflection, pagination limits, and buffer encoding, making it an effective tool for building hypermedia-driven APIs on top of Fortune.js without manual serialization overhead.

Common errors

Warnings

Install

Imports

Quickstart

This example sets up a basic Fortune.js server with the JSON API serializer, creating an HTTP listener that serves a 'users' and 'posts' resource type over a `/api` prefix.

const http = require('http');
const fortune = require('fortune');
const fortuneHTTP = require('fortune-http');
const jsonApiSerializer = require('fortune-json-api');

// Define your Fortune.js record types
const store = fortune({
  user: {
    email: String,
    name: String,
    posts: [Array('post'), 'author']
  },
  post: {
    title: String,
    content: String,
    author: ['user', 'posts']
  }
});

const listener = fortuneHTTP(store, {
  serializers: [
    // The `options` object here is optional.
    [ jsonApiSerializer, { prefix: '/api', jsonSpaces: 2 } ]
  ]
});

const server = http.createServer((request, response) =>
  listener(request, response)
    .catch(error => {
      console.error('API Error:', error);
      response.writeHead(500, { 'Content-Type': 'application/vnd.api+json' });
      response.end(JSON.stringify({ errors: [{ status: '500', title: 'Internal Server Error', detail: error.message }] }));
    })
);

const port = process.env.PORT ?? 8080;
server.listen(port, () => console.log(`JSON:API server listening on http://localhost:${port}/api`));

// Example: How to interact (e.g., in another file or via curl)
/*
curl -X POST -H "Content-Type: application/vnd.api+json" -d '{
  "data": {
    "type": "users",
    "attributes": {
      "email": "test@example.com",
      "name": "Test User"
    }
  }
}' http://localhost:8080/api/users

curl http://localhost:8080/api/users
*/

view raw JSON →