Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shorthand can reference other shorthands #346

Merged
merged 1 commit into from
Oct 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
});
});
});