Skip to content

Instantly share code, notes, and snippets.

@romain-gilliotte
Created February 22, 2022 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romain-gilliotte/46f2e832b4d9906dc5f1406a22265582 to your computer and use it in GitHub Desktop.
Save romain-gilliotte/46f2e832b4d9906dc5f1406a22265582 to your computer and use it in GitHub Desktop.
const { collection } = require("forest-express-sequelize");
collection("books", {
isSearchable: true,
fields: [
{
field: "title",
type: "String",
},
{
field: "author",
type: "Number", // this should be the type of the fk
reference: "persons.id",
},
],
});
const { collection } = require("forest-express-sequelize");
collection("persons", {
isSearchable: true,
fields: [
{
field: "firstname",
type: "String",
},
{
field: "lastname",
type: "String",
},
{
field: "books",
type: ["Number"], // type should be an array of the type of the target pk
reference: "books.id",
},
],
});
const { RecordSerializer } = require("forest-express-sequelize");
const express = require("express");
const router = express.Router();
const serializer = new RecordSerializer({ name: "books" });
const records = [
{
id: 1,
title: "Foundation",
author: { id: 1, firstname: "Isaac", lastname: "Asimov" },
},
{
id: 2,
title: "Beat the dealer",
author: { id: 2, firstname: "Edward O.", lastname: "Thorp" },
},
];
router.get("/books", async (req, res, next) => {
const output = await serializer.serialize(records, { count: records.length });
res.send(output);
});
router.get("/persons/:parentId/relationships/books", async (req, res, next) => {
const related = records.filter(
(r) => r.author.id === Number(req.params.parentId)
);
const output = await serializer.serialize(related, { count: related.length });
res.send(output);
});
router.get("/books/:id", async (req, res, next) => {
const record = records.find((r) => r.id === Number(req.params.id));
const output = await serializer.serialize(record);
res.send(output);
});
module.exports = router;
const { RecordSerializer } = require("forest-express-sequelize");
const express = require("express");
const router = express.Router();
const serializer = new RecordSerializer({ name: "persons" });
const records = [
{ id: 1, firstname: "Isaac", lastname: "Asimov" },
{ id: 2, firstname: "Edward O.", lastname: "Thorp" },
];
router.get("/persons", async (req, res, next) => {
const output = await serializer.serialize(records, { count: records.length });
res.send(output);
});
router.get("/persons/:id", async (req, res, next) => {
const record = records.find((r) => r.id === Number(req.params.id));
const output = await serializer.serialize(record);
res.send(output);
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment