@code-net/hal-api
v1.3.0
Published
This library makes it easier to create HAL (Hypertext Application Language) links in your API responses.
Readme
hal-api
This library makes it easier to create HAL (Hypertext Application Language) links in your API responses.
Installation
Install @code-net/hal-api to use the HAL link classes.
npm install @code-net/hal-apiUsage
Express
Usage with express API.
import { resolveHref, resolveLink } from '@code-net/hal-api';
import { halLinks } from '@code-net/hal-api/express';
const app = express();
app.use(halLinks({}));
app.get('/api/resource', (req, res) => {
const resource = {
name: 'Example Resource',
_links: {
self: { href: resolveHref('/resource'), method: 'GET' },
related: resolveLink({ href: '/related-resource' }),
},
};
res.json(resource);
});Make a request to your API:
curl http://localhost:3000/api/resource{
"name": "Example Resource",
"_links": {
"self": {
"href": "http://localhost:3000/api/resource",
"method": "GET"
},
"related": {
"href": "http://localhost:3000/api/related-resource",
"method": "GET"
}
}
}It can handle the X-Forwarded-* headers to build correct URLs, so you can use it behind a reverse proxy or load balancer.
curl -H "X-Forwarded-Proto: https" \
-H "X-Forwarded-Host: example.com" \
-H "X-Forwarded-Prefix: /api" \
http://localhost:3000/resourceResponse JSON:
{
"name": "Example Resource",
"_links": {
"self": {
"href": "https://example.com/api/resource",
"method": "GET"
},
"related": {
"href": "https://example.com/api/related-resource",
"method": "GET"
}
}
}Forcing base URL
If you are not able to setup your reverse proxy to send correct X-Forwarded-* headers, you can force the base URL like this:
app.use(halLinks({
protocol: 'https',
host: 'example.com:3000',
prefix: '/api',
}));Fastify
Usage with Fastify API.
import Fastify from 'fastify';
import halLinks from '@code-net/hal-api/fastify';
const app = Fastify();
app.register(halLinks, {
host: 'example.com', // optional
protocol: 'https', // optional
prefix: '/api', // optional
});NestJS
Usage with NestJS API.
import { Controller, Get, Post, Query } from '@nestjs/common';
import { routeLink } from '@code-net/hal-api/nestjs';
import { halLinks } from '@code-net/hal-api/express';
import { OtherController } from './other.controller';
// ...
const app: INestApplication = await NestFactory.create(AppModule);
app.use(halLinks());
// ...
@Controller('hals')
class HalController {
// The URL can contain slashes
@Get()
async get() {
return {
_links: {
post: routeLink(this, 'post', { params: { id: '123', foo: 'test', bar: ['A', 'B'] } }),
other: routeLink(OtherController, 'index'),
},
};
}
@Post(':id/post')
async post(@Query('foo') foo: string, @Query('bar') bar: string[]) {
// Logic here
}
}curl http://localhost:3000/hals{
"_links": {
"post": {
"href": "http://localhost:3000/hals/123/post?foo=test&bar[]=A&bar[]=B",
"method": "POST"
},
"other": {
"href": "http://localhost:3000/other",
"method": "GET"
}
}
}