import { model , Schema } from "mongoose" ; import { IApiKeyDocument , IApiKeyModel } from "../../typings/db/IApiKeyDocument" ; import { getConfig } from "../../typings/Configs" ; const ApiKeySchema = new Schema ( { name : { type : String , required : true } , owner : { type : String , required : true } , key : { type : String , required : true , index : true } , secret : { type : String , required : true } , createdAt : { type : Date , required : true } , updatedAt : { type : Date } , lastUsed : { type : Date } , allowedOrigins : [ String ] , allowedIps : [ String ] , allowedAgents : [ String ] , minDelay : Number } , { collection : "apikeys" } ) ; ApiKeySchema . methods . getMinDelay = async function ( this ) : Promise < number > { if ( this . minDelay ) { return this . minDelay ; } return ( await getConfig ( ) ) . delays . defaultApiKey ; } ; ApiKeySchema . methods . updateLastUsed = async function ( this , date ) : Promise < void > { return ApiKey . updateOne ( { key : this . key } , { $set : { lastUsed : date } } ) . exec ( ) . then ( ignored => { } ) ; } ; ApiKeySchema . statics . findKey = function ( key ) : Promise < IApiKeyDocument | null > { return ApiKey . findOne ( { key : key } ) . exec ( ) ; } ; export const ApiKey = model < IApiKeyDocument , IApiKeyModel > ( "ApiKey" , ApiKeySchema ) ;