Skip to content

Commit

Permalink
Shorthands can reference other shorthands (#346)
Browse files Browse the repository at this point in the history
  • Loading branch information
dolezel authored Oct 24, 2018
1 parent 1d44a76 commit a35740a
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
19 changes: 18 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,24 @@ const applyType = (type, extendingTypeShorthands = {}) => {
...extendingTypeShorthands
};
const options = typeof type === "string" ? { type } : type;
const ext = typeShorthands[options.type] || { type: options.type };
let ext = null;
const types = [options.type];
while (typeShorthands[types[types.length - 1]]) {
if (ext) {
delete ext.type;
}
ext = { ...typeShorthands[types[types.length - 1]], ...ext };
if (types.includes(ext.type)) {
throw new Error(
`Shorthands contain cyclic dependency: ${types.join(", ")}, ${ext.type}`
);
} else {
types.push(ext.type);
}
}
if (!ext) {
ext = { type: options.type };
}
return {
...ext,
...options,
Expand Down
42 changes: 41 additions & 1 deletion test/utils-test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { expect } = require("chai");
const { escapeValue, PgLiteral } = require("../lib/utils");
const { escapeValue, PgLiteral, applyType } = require("../lib/utils");

describe("lib/utils", () => {
describe(".escapeValue", () => {
Expand Down Expand Up @@ -49,4 +49,44 @@ describe("lib/utils", () => {
expect(escapeValue(value)).to.equal("");
});
});

describe(".applyType", () => {
it("convert string", () => {
const type = "type";

expect(applyType(type)).to.eql({ type });
});

it("apply id shorthand", () => {
expect(applyType("id")).to.eql({ type: "serial", primaryKey: true });
});

it("apply shorthand", () => {
const shorthandName = "type";
const shorthandDefinition = { type: "integer", defaultValue: 1 };
expect(
applyType(shorthandName, { [shorthandName]: shorthandDefinition })
).to.eql(shorthandDefinition);
});

it("apply recursive shorthand", () => {
const shorthands = {
ref: { type: `integer`, onDelete: `cascade` },
user: { type: `ref`, references: `users` }
};
expect(applyType("user", shorthands)).to.eql({
type: `integer`,
onDelete: `cascade`,
references: `users`
});
});

it("detect cycle in recursive shorthand", () => {
const shorthands = {
ref: { type: `user`, onDelete: `cascade` },
user: { type: `ref`, references: `users` }
};
expect(() => applyType("user", shorthands)).to.throw();
});
});
});

0 comments on commit a35740a

Please sign in to comment.