-
Notifications
You must be signed in to change notification settings - Fork 10
feat: add mongoose datasource #321
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
Closed
Closed
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
f60bd89
feat(mongoose): add list, create, delete, update actions
Scra3 0deab1b
feat: first aggregation
Scra3 574272b
feat: operator month
Scra3 0266d14
fix: refactor conditions
Scra3 c864603
feat: implements all operators
Scra3 37e4361
feat: nested fields
Scra3 0393639
feat: add rating
Scra3 777f710
refactor: aggregator
Scra3 e857515
feat: wip
Scra3 7977c43
fix: replace | by -
Scra3 63de52f
refactor: list
Scra3 9e92c7e
fix: adding schema
Scra3 6d811a5
test: adding a test to focus the bug with two many to many
Scra3 ff81e09
fix: wip
Scra3 3c61d36
fix: test and refacto
Scra3 ed50d69
fix: wip
Scra3 7db6803
fix: a bug
Scra3 6ef2359
fix: update case
Scra3 cdb996c
fix: create
Scra3 9863348
fix: delete
Scra3 7091613
fix: generator
Scra3 e8c0297
fix: wip
Scra3 799f49d
fix: huge refacto
Scra3 1120db8
fix: refacto for many to many
Scra3 99e3449
fix: refacto
Scra3 09401f6
refactor: code
Scra3 cabf359
fix: remove typo
Scra3 1492c92
fix: review
Scra3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,39 +1,245 @@ | ||
| /* eslint-disable max-classes-per-file, no-underscore-dangle */ | ||
| import { | ||
| AggregateResult, | ||
| Aggregation, | ||
| BaseCollection, | ||
| Caller, | ||
| ConditionTreeLeaf, | ||
| DataSource, | ||
| Filter, | ||
| ManyToManySchema, | ||
| PaginatedFilter, | ||
| Projection, | ||
| RecordData, | ||
| } from '@forestadmin/datasource-toolkit'; | ||
| import { Model } from 'mongoose'; | ||
| import { Model, PipelineStage, Schema, model as mongooseModel } from 'mongoose'; | ||
|
|
||
| import PipelineGenerator from './utils/pipeline-generator'; | ||
| import SchemaFieldsGenerator from './utils/schema-fields-generator'; | ||
|
|
||
| export default class MongooseCollection extends BaseCollection { | ||
| private readonly model: Model<RecordData>; | ||
| public readonly model: Model<RecordData>; | ||
|
|
||
| constructor(dataSource: DataSource, model: Model<RecordData>) { | ||
| super(model.modelName, dataSource); | ||
| this.model = model; | ||
| this.addFields(SchemaFieldsGenerator.buildFieldsSchema(model)); | ||
| } | ||
|
|
||
| async create(): Promise<RecordData[]> { | ||
| throw new Error('not implemented'); | ||
| async create(caller: Caller, data: RecordData[]): Promise<RecordData[]> { | ||
| this.parseJSONToNestedFieldsInPlace(data); | ||
| const records = await this.model.insertMany(data); | ||
|
|
||
| const ids = records.map(record => record._id); | ||
| const conditionTree = new ConditionTreeLeaf('_id', 'In', ids); | ||
|
|
||
| return this.list(caller, new Filter({ conditionTree }), new Projection()); | ||
| } | ||
|
|
||
| async list( | ||
| caller: Caller, | ||
| filter: PaginatedFilter, | ||
| projection: Projection, | ||
| ): Promise<RecordData[]> { | ||
| return this.model.aggregate(PipelineGenerator.find(this, this.model, filter, projection)); | ||
| } | ||
|
|
||
| async list(): Promise<RecordData[]> { | ||
| throw new Error('not implemented'); | ||
| async update(caller: Caller, filter: Filter, patch: RecordData): Promise<void> { | ||
| const ids = await this.list(caller, filter, new Projection('_id')); | ||
| await this.model.updateMany({ _id: ids.map(record => record._id) }, patch); | ||
| } | ||
|
|
||
| async update(): Promise<void> { | ||
| throw new Error('not implemented'); | ||
| async delete(caller: Caller, filter: Filter): Promise<void> { | ||
| const ids = await this.list(caller, filter, new Projection('_id')); | ||
| await this.model.deleteMany({ _id: ids.map(record => record._id) }); | ||
| } | ||
|
|
||
| async delete(): Promise<void> { | ||
| throw new Error('not implemented'); | ||
| async aggregate( | ||
| caller: Caller, | ||
| filter: Filter, | ||
| aggregation: Aggregation, | ||
| limit?: number, | ||
| ): Promise<AggregateResult[]> { | ||
| let pipeline = PipelineGenerator.find(this, this.model, filter, aggregation.projection); | ||
| pipeline = PipelineGenerator.group(aggregation, pipeline); | ||
| if (limit) pipeline.push({ $limit: limit }); | ||
|
|
||
| return MongooseCollection.formatRecords(await this.model.aggregate(pipeline)); | ||
| } | ||
|
|
||
| protected static formatRecords(records: RecordData[]): AggregateResult[] { | ||
| const results: AggregateResult[] = []; | ||
|
|
||
| records.forEach(record => { | ||
| const group = Object.entries(record?._id || {}).reduce((computed, [field, value]) => { | ||
| computed[field] = value; | ||
|
|
||
| return computed; | ||
| }, {}); | ||
|
|
||
| results.push({ value: record.value, group }); | ||
| }); | ||
|
|
||
| return results; | ||
| } | ||
|
|
||
| private parseJSONToNestedFieldsInPlace(data: RecordData[]) { | ||
| data.forEach(currentData => { | ||
| Object.entries(this.schema.fields).forEach(([fieldName, schema]) => { | ||
| if (schema.type === 'Column' && typeof schema.columnType === 'object') { | ||
| if (typeof currentData[fieldName] === 'string') { | ||
| currentData[fieldName] = JSON.parse(<string>currentData[fieldName]); | ||
| } | ||
| } | ||
| }); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| export class ManyToManyMongooseCollection extends MongooseCollection { | ||
| private readonly originCollection: MongooseCollection; | ||
| private readonly foreignCollection: MongooseCollection; | ||
| private readonly originFieldNameOfIds: string; | ||
|
|
||
| constructor( | ||
| originCollection: MongooseCollection, | ||
| foreignCollection: MongooseCollection, | ||
| originFieldNameOfIds: string, | ||
| manyToManyRelation: string, | ||
| ) { | ||
| const model = ManyToManyMongooseCollection.buildModel( | ||
| originCollection, | ||
| foreignCollection, | ||
| manyToManyRelation, | ||
| ); | ||
|
|
||
| super(originCollection.dataSource, model); | ||
| this.originCollection = originCollection; | ||
| this.foreignCollection = foreignCollection; | ||
| this.originFieldNameOfIds = originFieldNameOfIds; | ||
| } | ||
|
|
||
| override async create(caller: Caller, data: RecordData[]): Promise<RecordData[]> { | ||
| const records = await this.createManyToMany(data); | ||
| const ids = records.map(record => record._id); | ||
| const conditionTree = new ConditionTreeLeaf('_id', 'In', ids); | ||
|
|
||
| return this.list(caller, new Filter({ conditionTree }), new Projection()); | ||
| } | ||
|
|
||
| async aggregate(): Promise<AggregateResult[]> { | ||
| throw new Error('not implemented'); | ||
| override async list( | ||
| caller: Caller, | ||
| filter: PaginatedFilter, | ||
| projection: Projection, | ||
| ): Promise<RecordData[]> { | ||
| const { model } = this.originCollection; | ||
|
|
||
| return model.aggregate(this.buildListPipeline(model, filter, projection)); | ||
| } | ||
|
|
||
| override async update(caller: Caller, filter: Filter, patch: RecordData): Promise<void> { | ||
| return this.updateManyToMany(caller, filter, patch); | ||
| } | ||
|
|
||
| override async delete(caller: Caller, filter: Filter): Promise<void> { | ||
| return this.updateManyToMany(caller, filter); | ||
| } | ||
|
|
||
| override async aggregate( | ||
| caller: Caller, | ||
| filter: Filter, | ||
| aggregation: Aggregation, | ||
| limit?: number, | ||
| ): Promise<AggregateResult[]> { | ||
| const { model } = this.originCollection; | ||
| let pipeline = this.buildListPipeline(model, filter, aggregation.projection); | ||
| pipeline = PipelineGenerator.group(aggregation, pipeline); | ||
| if (limit) pipeline.push({ $limit: limit }); | ||
|
|
||
| return MongooseCollection.formatRecords(await model.aggregate(pipeline)); | ||
| } | ||
|
|
||
| private async createManyToMany(data: RecordData[]): Promise<RecordData[]> { | ||
| return Promise.all( | ||
| data.map(item => { | ||
| return this.originCollection.model.updateOne( | ||
| { _id: item[`${this.originCollection.name}_id`] }, | ||
| { | ||
| $addToSet: { [this.originFieldNameOfIds]: item[`${this.foreignCollection.name}_id`] }, | ||
| }, | ||
| ); | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| private async updateManyToMany( | ||
| caller: Caller, | ||
| filter: Filter, | ||
| patch?: RecordData, | ||
| ): Promise<void> { | ||
| const records = await this.list( | ||
| caller, | ||
| filter, | ||
| new Projection(`${this.originCollection.name}_id`, `${this.foreignCollection.name}_id`), | ||
| ); | ||
|
|
||
| for (const record of records) { | ||
| // improve by grouping by origin id | ||
| // eslint-disable-next-line no-await-in-loop | ||
| await this.originCollection.model.updateOne( | ||
| { _id: record[`${this.originCollection.name}_id`] }, | ||
| { | ||
| $pull: { [this.originFieldNameOfIds]: record[`${this.foreignCollection.name}_id`] }, | ||
| }, | ||
| ); | ||
|
|
||
| if (patch) { | ||
| // eslint-disable-next-line no-await-in-loop | ||
| await this.originCollection.model.updateOne( | ||
| { _id: patch[`${this.originCollection.name}_id`] }, | ||
| { | ||
| $addToSet: { [this.originFieldNameOfIds]: patch[`${this.foreignCollection.name}_id`] }, | ||
| }, | ||
| ); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private buildListPipeline( | ||
| model: Model<RecordData>, | ||
| filter: Filter, | ||
| projection: Projection, | ||
| ): PipelineStage[] { | ||
| const allFilter = new PaginatedFilter({}); | ||
| const allProjection = new Projection(); | ||
| let pipeline = PipelineGenerator.find(this.originCollection, model, allFilter, allProjection); | ||
| pipeline = PipelineGenerator.emulateManyToManyCollection( | ||
| model, | ||
| this.originFieldNameOfIds, | ||
| this.originCollection.name, | ||
| this.foreignCollection.name, | ||
| pipeline, | ||
| ); | ||
|
|
||
| return PipelineGenerator.find(this, model, filter, projection, pipeline); | ||
| } | ||
|
|
||
| private static buildModel( | ||
| originCollection: MongooseCollection, | ||
| foreignCollection: MongooseCollection, | ||
| manyToManyRelation: string, | ||
| ): Model<RecordData> { | ||
| const { foreignKey, originKey, throughCollection } = foreignCollection.schema.fields[ | ||
| manyToManyRelation | ||
| ] as ManyToManySchema; | ||
| const schema = new Schema( | ||
| { | ||
| [foreignKey]: { type: Schema.Types.ObjectId, ref: originCollection.name }, | ||
| [originKey]: { type: Schema.Types.ObjectId, ref: foreignCollection.name }, | ||
| }, | ||
| { _id: false }, | ||
| ); | ||
|
|
||
| return mongooseModel(throughCollection, schema, null, { overwriteModels: true }); | ||
| } | ||
| } |
35 changes: 35 additions & 0 deletions
35
packages/datasource-mongoose/src/utils/field-name-generator.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| export default class FieldNameGenerator { | ||
| static generateManyToOne(fieldName: string, modelName: string): string { | ||
| return `${fieldName}__${modelName.split('_').pop()}__manyToOne`; | ||
| } | ||
|
|
||
| static generateOneToMany(foreignCollectionName: string, foreignKey: string): string { | ||
| return `${foreignCollectionName}__${foreignKey}__oneToMany`; | ||
| } | ||
|
|
||
| static generateThroughFieldName( | ||
| modelName: string, | ||
| foreignCollectionName: string, | ||
| fieldName: string, | ||
| ): string { | ||
| return `${modelName}__${foreignCollectionName}__${fieldName}`; | ||
| } | ||
|
|
||
| static getOriginFieldNameOfIds(name: string) { | ||
| return name.split('_').pop(); | ||
| } | ||
|
|
||
| static generateManyToManyName( | ||
| foreignCollectionName: string, | ||
| originKey: string, | ||
| throughCollection: string, | ||
| ): string { | ||
| return `${foreignCollectionName}__${originKey}__${this.getOriginFieldNameOfIds( | ||
| throughCollection, | ||
| )}`; | ||
| } | ||
|
|
||
| static generateKey(name: string): string { | ||
| return `${name}_id`; | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this example will be partially removed after the review.