当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript ObjectID.isValid方法代码示例

本文整理汇总了TypeScript中mongodb.ObjectID.isValid方法的典型用法代码示例。如果您正苦于以下问题:TypeScript ObjectID.isValid方法的具体用法?TypeScript ObjectID.isValid怎么用?TypeScript ObjectID.isValid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mongodb.ObjectID的用法示例。


在下文中一共展示了ObjectID.isValid方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: function

export default async function(ctx: Koa.Context) {
	// Validate id
	if (!mongodb.ObjectID.isValid(ctx.params.id)) {
		ctx.throw(400, 'incorrect id');
		return;
	}

	const fileId = new mongodb.ObjectID(ctx.params.id);

	// Fetch drive file
	const file = await DriveFile.findOne({ _id: fileId });

	if (file == null) {
		ctx.status = 404;
		await send(ctx, '/dummy.png', { root: assets });
		return;
	}

	if (file.metadata.deletedAt) {
		ctx.status = 410;
		await send(ctx, '/tombstone.png', { root: assets });
		return;
	}

	if (file.metadata.withoutChunks) {
		ctx.status = 204;
		return;
	}

	const sendRaw = async () => {
		const bucket = await getDriveFileBucket();
		const readable = bucket.openDownloadStream(fileId);
		readable.on('error', commonReadableHandlerGenerator(ctx));
		ctx.set('Content-Type', file.contentType);
		ctx.body = readable;
	};

	if ('thumbnail' in ctx.query) {
		const thumb = await DriveFileThumbnail.findOne({
			'metadata.originalId': fileId
		});

		if (thumb != null) {
			ctx.set('Content-Type', 'image/jpeg');
			const bucket = await getDriveFileThumbnailBucket();
			ctx.body = bucket.openDownloadStream(thumb._id);
		} else {
			await sendRaw();
		}
	} else {
		if ('download' in ctx.query) {
			ctx.set('Content-Disposition', 'attachment');
		}

		await sendRaw();
	}
}
开发者ID:ha-dai,项目名称:Misskey,代码行数:57,代码来源:send-drive-file.ts

示例2: callback

    (f = (err, task) => {
      if (err) return void callback(err);

      if (!task) return void callback(null, tasks, null);

      if (task.timestamp) task.timestamp = +task.timestamp;
      if (task.expiry) task.expiry = +task.expiry;
      if (task.timestamp >= timestamp)
        return void callback(null, tasks, +task.timestamp);
      task._id = String(task._id);

      tasks.push(task);

      // For API compatibility
      if (task.name === "download" && task.file) {
        let q;
        if (ObjectID.isValid(task.file))
          q = { _id: { $in: [task.file, new ObjectID(task.file)] } };
        else q = { _id: task.file };

        filesCollection.find(q).toArray((err, res) => {
          if (err) return void callback(err);

          if (res[0]) {
            if (!task.fileType) task.fileType = res[0].metadata.fileType;

            if (!task.fileName)
              task.fileName = res[0].filename || res[0]._id.toString();
          }

          cur.next(f);
        });
      } else {
        cur.next(f);
      }
    })
开发者ID:zaidka,项目名称:genieacs,代码行数:36,代码来源:db.ts

示例3: function

 normalizedId: function (id) {
     if (ObjectID.isValid(id)) {
         return new ObjectID(id);
     }
     else { return id; }
 },
开发者ID:lmaran,项目名称:logspace,代码行数:6,代码来源:mongo.service.ts

示例4:

export const isAnId = (x: any) => mongo.ObjectID.isValid(x);
开发者ID:ha-dai,项目名称:Misskey,代码行数:1,代码来源:cafy-id.ts

示例5: updateValue

    async updateValue(masterTable: string, field: string, entityId: string, value: any,upsert: boolean): Promise<void> {
        if (!ObjectID.isValid(entityId)) {
            return Promise.reject(new Error(entityId + " is not a valid object id"))
        }
        try {
            if (!this.db) {
                await this.connect()
            }

            if (typeof this.masterTables === "undefined") {
                this.masterTables = await this.repository.masterTableRepository.findAll()
            }

            let targetMasterTable: MasterTable
            targetMasterTable = this.masterTables.find(m=> m.id === masterTable)

            let cleanMasterTableName = StringExtensions.clean(masterTable).toLowerCase()

            if (typeof targetMasterTable === "undefined") {
                targetMasterTable = this.masterTables.find(m=> m.cleanSingularName.toLowerCase() === cleanMasterTableName)
            }
            if (typeof targetMasterTable === "undefined") {
                targetMasterTable = this.masterTables.find(m=> m.cleanPluralName.toLowerCase() === cleanMasterTableName)
            }
            if (typeof targetMasterTable === "undefined") {
                return Promise.reject(`Master table ${masterTable} not found`)
            }

            let targetField: MasterTableField
            targetField = targetMasterTable.fields.find(f=> f.id === field)

            let cleanFieldName = StringExtensions.clean(field).toLowerCase()
            if (typeof targetField === "undefined") {
                targetField = targetMasterTable.fields.find(f=> f.cleanName.toLowerCase() === cleanFieldName)
            }
            if (typeof targetField === "undefined") {
                return Promise.reject(`Field ${field} not found on master table ${targetMasterTable.singularName}`)
            }

            let update = {
                $set: {}
            }

            if (targetField.type === "EntityReference") {
                return this.updateEntityReferenceField(targetMasterTable, targetField, entityId, value,upsert)
            }
            else {
                return new Promise <void>((resolve, reject) => {


                    switch (targetField.type) {
                        case "Text":
                            if (typeof value !== "string") {
                                reject(`Value for ${targetField.cleanName} must be a string rather than ${typeof value}`)
                            } else {
                                update.$set[targetField.id] = value
                            }
                            break

                        case "Number":
                            if (typeof value !== "number") {
                                reject(`Value for ${targetField.cleanName} must be a number rather than ${typeof value}`)
                            } else {
                                update.$set[targetField.id] = value
                            }
                            break

                        case "Boolean":
                            if (typeof value !== "boolean") {
                                reject(`Value for ${targetField.cleanName} must be a boolean rather than ${typeof value}`)
                            } else {
                                update.$set[targetField.id] = value
                            }
                            break

                        case "DateTime":
                            if ((value instanceof Date) !== true) {
                                reject(`Value for ${targetField.cleanName} must be a date rather than ${typeof value}`)
                            } else {
                                update.$set[targetField.id] = value
                            }
                            break
                    }


                    let collection = this.db.collection(targetMasterTable.id);

                    let _id = new ObjectID(entityId)
                    let query = {"_id": _id};

                    collection.updateOne(query, update, {upsert: upsert, w: 1}, (err, result) => {
                        if (err) {
                            reject(err);
                        } else {
                            if (result.result.ok !== 1) {
                                reject("Unknown error occurred")
                            }

                            resolve();
                        }
//.........这里部分代码省略.........
开发者ID:quick-tracks,项目名称:quick-tracks-node-client,代码行数:101,代码来源:DataWriter.ts

示例6: getEntityRefUpdates

    private async getEntityRefUpdates(masterTable: MasterTable, field: MasterTableField, entityId: string,  value: string): Promise <EntityRefUpdate[]> {
        let results: EntityRefUpdate[] = []

        let existingIds: string[] = []
        let newIds: string[] = []
        if (value !== null && value !== "" ) {
            newIds = value.split(",")
        }
        for(let newId of newIds) {
            if (!ObjectID.isValid(newId)) {
                throw new Error(newId + " is not a valid ID")
            }
        }

        let existingDoc = await this.docFetcher.findById(masterTable.id, entityId, [field.id])
        if (existingDoc !== null && typeof existingDoc[field.id] !== "undefined") {
            for (let existingRef of existingDoc[field.id]) {
                existingIds.push(existingRef.oid.toString())
            }
        }

        if (newIds.length > 1 && !field.referencesMany) {
            throw new Error("This field cannot reference many entities")
        }
        
        for(let newId of newIds) {
            //if (existingIds.indexOf(newId) === -1) {

                //Add new ids to normal table
                results.push({
                    masterTableId: masterTable.id,
                    fieldId: field.id,
                    entityId: new ObjectID(entityId),
                    entityToAddRemoveMasterTableId: field.targetMasterTable.id,
                    entityIdToAddRemove: new ObjectID(newId),
                    removeReference: false

                })

                //Add reciprocal reference to target table
                results.push({
                    masterTableId: field.targetMasterTable.id,
                    fieldId: field.targetField.id,
                    entityId: new ObjectID(newId),
                    entityToAddRemoveMasterTableId: masterTable.id,
                    entityIdToAddRemove:  new ObjectID(entityId),
                    removeReference: false
                })
            //}
        }

        for (let existingId of existingIds) {
            if (newIds.indexOf(existingId) === -1) {

                //Remove old ids from normal table
                results.push({
                    masterTableId: masterTable.id,
                    fieldId: field.id,
                    entityId: new ObjectID(entityId),
                    entityToAddRemoveMasterTableId: field.targetMasterTable.id,
                    entityIdToAddRemove: new ObjectID(existingId),
                    removeReference: true
                })

                //Remove reciprocal reference from target table
                results.push({
                    masterTableId: field.targetMasterTable.id,
                    fieldId: field.targetField.id,
                    entityId: new ObjectID(existingId),
                    entityToAddRemoveMasterTableId: masterTable.id,
                    entityIdToAddRemove:  new ObjectID(entityId),
                    removeReference: true
                })
            }
        }


        return Promise.resolve(results)
    }
开发者ID:quick-tracks,项目名称:quick-tracks-node-client,代码行数:79,代码来源:DataWriter.ts


注:本文中的mongodb.ObjectID.isValid方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。