Schema.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { Attribute } from "./types/Attribute";
  2. import { Document } from "./types/Document";
  3. export enum Types {
  4. String,
  5. Number,
  6. Date,
  7. Boolean,
  8. ObjectId,
  9. Array,
  10. // Map,
  11. Schema
  12. }
  13. export const createAttribute = ({
  14. type,
  15. required,
  16. restricted,
  17. item,
  18. schema,
  19. defaultValue,
  20. unique,
  21. min,
  22. max,
  23. enumValues
  24. }: Partial<Attribute> & { type: Attribute["type"] }) => ({
  25. type,
  26. required: required ?? true,
  27. restricted: restricted ?? false,
  28. item,
  29. schema,
  30. defaultValue,
  31. unique: unique ?? false,
  32. min,
  33. max,
  34. enumValues
  35. });
  36. export default class Schema {
  37. private document: Document;
  38. private timestamps: boolean;
  39. private version: number;
  40. public constructor(schema: {
  41. document: Document;
  42. timestamps?: boolean;
  43. version?: number;
  44. }) {
  45. this.document = {
  46. _id: createAttribute({ type: Types.ObjectId }),
  47. ...schema.document
  48. };
  49. this.timestamps = schema.timestamps ?? true;
  50. this.version = schema.version ?? 1;
  51. if (this.timestamps) {
  52. this.document.createdAt = createAttribute({
  53. type: Types.Date
  54. });
  55. this.document.updatedAt = createAttribute({
  56. type: Types.Date
  57. });
  58. }
  59. }
  60. public getDocument() {
  61. return this.document;
  62. }
  63. public getVersion() {
  64. return this.version;
  65. }
  66. }