node.jsexpresshateoas

HATEOAS in Node.js


I want to use express-hateoas-links package but it is not working:

module "C:/Users/me/Documents/node/express-project/node_modules/express-hateoas-links/index" Could not find a declaration file for module 'express-hateoas-links'. 'C:/Users/me/Documents/node/express-project/node_modules/express-hateoas-links/index.js' implicitly has an 'any' type. Try npm i --save-dev @types/express-hateoas-links if it exists or add a new declaration (.d.ts) file containing declare module 'express-hateoas-links';ts(7016)

import express, { json } from 'express';
import hateoasLinker from 'express-hateoas-links';

const friends = [
  {
    id: 0,
    name: 'XXX'
  },
  ...
];

app.use(hateoasLinker);

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

app.use(json());

app.get('/friends', (req, res) => {
  res.json(friends,[
    { rel: "self", method: "GET", href: 'http://localhost:3000/friends' },
    { rel: "create", method: "POST", title: 'Create Friends', href: 'http://localhost:3000/friends' }
  ]);
});

The application works but response does not contains links due to the error. ???


Solution

  • I remember when I tried to use HATEAOS library can't use with an array JSON response, but I tried to use a map method

    const response = catalogo.map(x => {
      return {
        name: x.name,
        description: x.description,
        href: {
          rel: "productos",
          method: "GET",
          href: 'http://localhost:8080/ver-productos/' + x._id
        },
      }
    });
    
    res.json({
      from,
      limit,
      total,
      response
    });
    

    This worked for me.