Fortune JSON API Serializer
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
-
ReferenceError: require is not defined
cause Attempting to use `require()` in an ES Module environment (e.g., in a `.mjs` file or when `"type": "module"` is set in `package.json`) without a transpilation step.fixChange `const jsonApiSerializer = require('fortune-json-api')` to `import jsonApiSerializer from 'fortune-json-api'`. Ensure your Node.js version supports ESM or configure a bundler like Webpack/Rollup if targeting older environments. -
TypeError: (0 , fortune_json_api_1.default) is not a function
cause Incorrectly importing a CommonJS default export in an ES Module context, often due to a mismatch in how transpilers or Node.js handle default exports from CJS modules.fixTry `import * as jsonApiModule from 'fortune-json-api'; const jsonApiSerializer = jsonApiModule.default;` or simplify to `import jsonApiSerializer from 'fortune-json-api'` if your environment supports it. Often, setting `esModuleInterop: true` in `tsconfig.json` for TypeScript projects can also resolve this. -
Error: Invalid JSON API payload
cause The incoming HTTP request body does not conform to the JSON API specification's structure or content rules, leading to validation failure by the serializer.fixVerify that your client-side requests adhere strictly to the JSON API specification, especially regarding the `data`, `type`, `id`, `attributes`, and `relationships` keys in the request body. Common mistakes include wrong `Content-Type` header (should be `application/vnd.api+json`) or missing `data` wrapper. -
Cannot find module 'fortune' or Cannot find module 'fortune-http'
cause The required peer dependencies `fortune` or `fortune-http` are not installed or are not resolvable in the current project's `node_modules`.fixInstall the missing packages: `npm install fortune fortune-http`.
Warnings
- breaking Prior to Fortune.js v1.0.0-rc.13, the JSON API serializer was bundled directly within the `fortune` package. This changed to an external module, `fortune-json-api`, requiring explicit installation and import for any projects migrating from very old `fortune` versions (pre-1.0.0-rc.13) to newer ones.
- gotcha This library is tightly coupled with `fortune` and `fortune-http`. Mismatched major versions of these peer dependencies can lead to unexpected behavior or runtime errors. Always check the `fortune-json-api`'s `package.json` for compatible peer dependency ranges.
- gotcha The `prefix` option, if set to a path starting with `/`, will rewrite URLs relative to that prefix. For example, a prefix of `/api` will make requests for `/api/users/1` map to the `users` resource with ID `1`. Misunderstanding this behavior can lead to incorrect routing or URL generation.
- gotcha This package is primarily designed for CommonJS (`require`) environments, and all official examples use this syntax. While it might work with ESM via bundlers or Node.js's compatibility layers, explicit ESM support (e.g., named exports, `.mjs` files) is not documented, which can lead to import errors in pure ESM projects.
Install
-
npm install fortune-json-api -
yarn add fortune-json-api -
pnpm add fortune-json-api
Imports
- jsonApiSerializer
const jsonApiSerializer = require('fortune-json-api')import jsonApiSerializer from 'fortune-json-api'
- jsonApiSerializer
const jsonApiSerializer = require('fortune-json-api')
Quickstart
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
*/