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

Adding support for types #378

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
63 changes: 63 additions & 0 deletions src/compile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,10 @@ describe("compileBSON", () => {
description: "Number",
bsonType: "number",
},
double: {
description: "Double",
bsonType: "double",
},
boolean: {
description: "Boolean",
bsonType: "bool",
Expand Down Expand Up @@ -204,6 +208,65 @@ describe("compileBSON", () => {
getExpected("bson-types-with-imports-2")
);
});

test(`BSON types ObjectId`, async () => {
const schema = {
title: "UserDoc",
description: "User object",
bsonType: "object",
additionalProperties: false,
required: [],
properties: {
_id: {
bsonType: "objectId",
},
},
};

expect(await compileBSON(schema)).toBe(getExpected("bson-types-object-id"));
});

test(`BSON types geo-json`, async () => {
const schema = {
title: "UserDoc",
description: "User object",
bsonType: "object",
additionalProperties: false,
required: [],
properties: {
// https://www.leighhalliday.com/mongodb-geojson-schema-validation
location: {
bsonType: "object",
required: ["type", "coordinates"],
properties: {
type: {
bsonType: "string",
enum: ["Point"],
},
coordinates: {
bsonType: ["array"],
minItems: 2,
maxItems: 2,
items: [
{
bsonType: "double",
minimum: -180,
maximum: 180,
},
{
bsonType: "double",
minimum: -90,
maximum: 90,
},
],
},
},
},
},
};

expect(await compileBSON(schema)).toBe(getExpected("bson-types-geo-json"));
});
});

describe("compileBSON with banner comments", () => {
Expand Down
29 changes: 18 additions & 11 deletions src/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ function format(text: string, options?: prettier.Options): string {
* https://docs.mongodb.com/manual/reference/operator/query/type/#document-type-available-types
*
* [X] number
* [ ] double
* [x] double
* [X] string
* [ ] object
* [ ] array
* [ ] binData
* [ ] undefined -- Deprecated
* [ ] objectId
* [x] objectId
* [X] bool
* [X] date
* [X] null
Expand All @@ -55,9 +55,11 @@ const bsonToTs = new Map([
["string", "string"],
["bool", "boolean"],
["date", "Date"],
["double", "number"],
["null", "null"],
["int", "number"],
["decimal", "Decimal128"],
["objectId", "ObjectId"],
]);

/**
Expand Down Expand Up @@ -111,22 +113,22 @@ function setTsType(schema: JsonValue): JsonValue {
/**
* Recursively checks if a schema relies on the Decimal128 BSON type anywhere
*/
function hasDecimal128(schema: JsonValue): boolean {
function hasType(schema: JsonValue, typeName: string): boolean {
if (schema === null || typeof schema !== "object") {
return false;
}

if (Array.isArray(schema)) {
return schema.some(hasDecimal128);
return schema.some((schema) => hasType(schema, typeName));
}

return Object.entries(schema).some(([key, value]) => {
if (key === "bsonType") {
if (value === "decimal") return true;
if (Array.isArray(value)) return value.includes("decimal");
if (value === typeName) return true;
if (Array.isArray(value)) return value.includes(typeName);
}

if (typeof value === "object") return hasDecimal128(value);
if (typeof value === "object") return hasType(value, typeName);

return false;
});
Expand All @@ -148,10 +150,15 @@ export async function compileBSON(
const baseBanner = options?.bannerComment || defaultOptions.bannerComment;

// Import Decimal128 if the type annotations use it
const bannerComment = (hasDecimal128(schema)
? [...baseBanner, `import { Decimal128 } from "mongodb";`]
: baseBanner
).join("\n");
let comments = [...baseBanner];
if (hasType(schema, "decimal")) {
comments.push('import { Decimal128 } from "mongodb";');
}
// Import ObjectId if the type annotations use it
if (hasType(schema, "objectId")) {
comments.push('import { ObjectId } from "mongodb";');
}
const bannerComment = comments.join("\n");

const compileJSONOptions: Partial<CompileJSONOptions> = {
bannerComment,
Expand Down
20 changes: 20 additions & 0 deletions src/expected/bson-types-geo-json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* eslint-disable */

/**
* This file was automatically generated by bson-schema-to-typescript.
* https://www.npmjs.com/package/bson-schema-to-typescript
*
* Do not modify it by hand. Instead, modify the MongoDB $jsonSchema validator,
* and run bson2ts to regenerate this file.
*/

/**
* User object
*/
export interface UserDoc {
location?: {
type: "Point";
coordinates: [number, number];
[k: string]: unknown;
};
}
17 changes: 17 additions & 0 deletions src/expected/bson-types-object-id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* eslint-disable */

/**
* This file was automatically generated by bson-schema-to-typescript.
* https://www.npmjs.com/package/bson-schema-to-typescript
*
* Do not modify it by hand. Instead, modify the MongoDB $jsonSchema validator,
* and run bson2ts to regenerate this file.
*/
import { ObjectId } from "mongodb";

/**
* User object
*/
export interface UserDoc {
_id?: ObjectId;
}
4 changes: 4 additions & 0 deletions src/expected/bson-types-with-imports-1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ export interface UserDoc {
* Number
*/
number?: number;
/**
* Double
*/
double?: number;
/**
* Boolean
*/
Expand Down