forked from storj-archived/bridge
-
Notifications
You must be signed in to change notification settings - Fork 2
refactor(users-buckets): migrate users and bucket models #211
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| import crypto from "crypto"; | ||
| import { Schema, Document, Connection, Types } from "mongoose"; | ||
| import { validate as uuidValidate, version as uuidVersion } from "uuid"; | ||
| const errors = require("storj-service-error-types"); | ||
|
|
||
| interface IBucket extends Document { | ||
| storage: number; | ||
| transfer: number; | ||
| status: "Active" | "Inactive"; | ||
| pubkeys: string[]; | ||
| user: string; | ||
| userId: string; | ||
| name: string; | ||
| maxFrameSize: number; | ||
| created: Date; | ||
| publicPermissions: ("PUSH" | "PULL")[]; | ||
| encryptionKey: string; | ||
| } | ||
|
|
||
| const BucketSchema = new Schema<IBucket>( | ||
| { | ||
| storage: { type: Number, default: 0 }, | ||
| transfer: { type: Number, default: 0 }, | ||
| status: { | ||
| type: String, | ||
| enum: ["Active", "Inactive"], | ||
| default: "Active", | ||
| }, | ||
| pubkeys: [{ type: String, ref: "PublicKey" }], | ||
| user: { type: String, ref: "User" }, | ||
| userId: { | ||
| type: String, | ||
| required: true, | ||
| validate: { | ||
| validator: (value: string) => | ||
| uuidValidate(value) && uuidVersion(value) === 4, | ||
| message: "Invalid UUID", | ||
| }, | ||
| ref: "User", | ||
| }, | ||
| name: { | ||
| type: String, | ||
| default: () => "Bucket-" + crypto.randomBytes(3).toString("hex"), | ||
| }, | ||
| maxFrameSize: { type: Number, default: -1 }, | ||
| created: { type: Date, default: Date.now }, | ||
| publicPermissions: { | ||
| type: [{ type: String, enum: ["PUSH", "PULL"] }], | ||
| default: [], | ||
| }, | ||
| encryptionKey: { type: String, default: "" }, | ||
| }, | ||
| { | ||
| statics: { | ||
| async create( | ||
| user: { _id: string; uuid: string }, | ||
| data: { pubkeys?: string[]; name?: string }, | ||
| callback: (err: Error | null, bucket?: IBucket) => void, | ||
| ) { | ||
| const Bucket = this; | ||
|
|
||
| const bucket = new Bucket({ | ||
| status: "Active", | ||
| pubkeys: data.pubkeys, | ||
| user: user._id, | ||
| userId: user.uuid, | ||
| }); | ||
|
|
||
| if (data.name) { | ||
| bucket.name = data.name; | ||
| } | ||
|
|
||
| try { | ||
| await bucket.save(); | ||
|
|
||
| const savedBucket = await Bucket.findOne({ | ||
| _id: bucket._id, | ||
| }); | ||
| if (!savedBucket) { | ||
| return callback( | ||
| new errors.InternalError( | ||
| "Failed to load created bucket", | ||
| ), | ||
| ); | ||
| } | ||
|
|
||
| callback(null, savedBucket); | ||
| } catch (err: any) { | ||
| if (err.code === 11000) { | ||
| return callback( | ||
| new errors.ConflictError( | ||
| "Name already used by another bucket", | ||
| ), | ||
| ); | ||
| } | ||
| callback(new errors.InternalError(err.message)); | ||
| } | ||
| }, | ||
| }, | ||
| }, | ||
| ); | ||
|
|
||
| BucketSchema.index({ user: 1 }); | ||
| BucketSchema.index({ userId: 1 }); | ||
| BucketSchema.index({ created: 1 }); | ||
| BucketSchema.index({ user: 1, name: 1 }, { unique: true }); | ||
|
|
||
| BucketSchema.set("toObject", { | ||
| transform: (doc: any, ret: Record<string, any>) => { | ||
| delete ret.__v; | ||
| delete ret._id; | ||
| ret.id = doc._id; | ||
| }, | ||
| }); | ||
|
|
||
| export = (connection: Connection) => | ||
| connection.model<IBucket>("Bucket", BucketSchema); |
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,117 @@ | ||
| 'use strict'; | ||
|
|
||
| const assert = require('assert'); | ||
| const mongoose = require('mongoose'); | ||
|
|
||
| /** | ||
| * MongoDB storage interface | ||
| * @constructor | ||
| * @param {String} mongoURI | ||
| * @param {Object} mongoOptions | ||
| * @param {Object} storageOptions | ||
| */ | ||
| function Database(mongoURI, mongoOptions, storageOptions) { | ||
| if (!(this instanceof Database)) { | ||
| return new Database(mongoURI, mongoOptions, storageOptions); | ||
| } | ||
|
|
||
| assert(typeof mongoOptions === 'object', 'Invalid mongo options supplied'); | ||
|
|
||
| this._uri = mongoURI; | ||
| this._options = mongoOptions; | ||
| this._log = (storageOptions && storageOptions.logger) || { | ||
| info: console.log, | ||
| debug: console.log, | ||
| error: console.error, | ||
| warn: console.warn, | ||
| }; | ||
|
|
||
| this._connect(); | ||
| } | ||
|
|
||
| Database.externalModels = require('storj-service-storage-models').models; | ||
| Database.localModels = { | ||
| Bucket: require('./bucket'), | ||
| User: require('./user'), | ||
| }; | ||
| Database.constants = require('../constants'); | ||
|
|
||
| /** | ||
| * Connects to the database | ||
| */ | ||
| Database.prototype._connect = function () { | ||
| const opts = Object.assign({ ssl: false }, this._options); | ||
|
|
||
| if (opts.server) { | ||
| this._log.warn( | ||
| 'Deprecated \'server\' option detected in database configuration. ' + | ||
| 'This option was removed in MongoDB driver 4.x and will be ignored. ' + | ||
| 'Please remove it from your configuration.' | ||
| ); | ||
| delete opts.server; | ||
| } | ||
|
|
||
| this._log.info('opening database connection at %s', this._uri); | ||
|
|
||
| this.connection = mongoose.createConnection(this._uri, opts); | ||
|
|
||
| this.connection.on('error', (err) => { | ||
| this._log.error('database connection error: %s', err.message); | ||
| }); | ||
|
|
||
| this.connection.on('disconnected', () => { | ||
| this._log.warn('disconnected from database'); | ||
| }); | ||
|
|
||
| this.connection.on('connected', () => { | ||
| this._log.info('connected to database'); | ||
| }); | ||
|
|
||
| this.models = this._createBoundModels(); | ||
| }; | ||
|
|
||
| /** | ||
| * Return a dictionary of models bound to this connection | ||
| */ | ||
| Database.prototype._createBoundModels = function () { | ||
| const bound = {}; | ||
|
|
||
| const allModels = { | ||
| ...Database.externalModels, | ||
| ...Database.localModels, | ||
| }; | ||
|
|
||
| for (const model in allModels) { | ||
| bound[model] = allModels[model](this.connection); | ||
| } | ||
|
|
||
| return bound; | ||
| }; | ||
|
|
||
| /** | ||
| * Returns a promise that resolves when the connection is ready | ||
| */ | ||
| Database.prototype.ready = function () { | ||
| return new Promise((resolve, reject) => { | ||
| if (this.connection.readyState === 1) { | ||
| return resolve(); | ||
| } | ||
| this.connection.once('connected', resolve); | ||
| this.connection.once('error', reject); | ||
| }); | ||
| }; | ||
|
|
||
| /** | ||
| * Creates a Database instance from a config object | ||
| * @param {Object} storageConfig - { mongoUrl, mongoOpts } | ||
| * @param {Object} [logger] | ||
| */ | ||
| Database.createFromConfig = function (storageConfig, logger) { | ||
| return new Database( | ||
| storageConfig.mongoUrl, | ||
| storageConfig.mongoOpts, | ||
| logger ? { logger } : {} | ||
| ); | ||
| }; | ||
|
|
||
| module.exports = Database; | ||
Oops, something went wrong.
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.
The models initialize their connection in the external library so I copied the same file to this repository to initialize the connection for external and local models instead of using https://github.com/internxt/service-storage-models/blob/master/index.js