1- import mongoose , { Schema , Model , InferSchemaType } from 'mongoose' ;
1+ import { Schema , Model , InferSchemaType , model , Document } from 'mongoose' ;
22
3- interface IApiKey {
4- label : string ;
5- lastUsedAt : Date ;
6- hashedKey : string ;
7- }
8-
9- interface ApiKeyVirtuals {
10- id : string ;
11- }
12-
13- type ApiKeyModelType = Model < IApiKey , { } , { } , ApiKeyVirtuals > ;
14-
15- interface MongooseTimestamps {
16- createdAt : Date ;
17- updatedAt : Date ;
18- }
19-
20- interface SanitisedApiKey
21- extends Omit < IApiKey , 'hashedKey' > ,
22- ApiKeyVirtuals ,
23- Pick < MongooseTimestamps , 'createdAt' > { }
24-
25- export const apiKeySchema = new Schema <
26- IApiKey ,
27- ApiKeyModelType ,
28- { } ,
29- { } ,
30- ApiKeyVirtuals
31- > (
3+ export const apiKeySchema = new Schema (
324 {
335 label : { type : String , default : 'API Key' } ,
346 lastUsedAt : { type : Date } ,
@@ -41,12 +13,30 @@ apiKeySchema.virtual('id').get(function getApiKeyId() {
4113 return this . _id . toHexString ( ) ;
4214} ) ;
4315
16+ interface ApiKeyVirtuals {
17+ id : string ;
18+ }
19+
20+ type ApiKeySchemaType = InferSchemaType < typeof apiKeySchema > ;
21+
22+ export type ApiKeyDocument = Document & ApiKeySchemaType & ApiKeyVirtuals ;
23+
24+ export type ApiKeyModel = Model < ApiKeyDocument > ;
25+
26+ export const ApiKey = model < ApiKeyDocument , ApiKeyModel > (
27+ 'ApiKey' ,
28+ apiKeySchema
29+ ) ;
30+
31+ interface SanitisedApiKey
32+ extends Pick < ApiKeyDocument , 'id' | 'label' | 'lastUsedAt' | 'createdAt' > { }
33+
4434/**
4535 * When serialising an APIKey instance, the `hashedKey` field
4636 * should never be exposed to the client. So we only return
4737 * a safe list of fields when toObject and toJSON are called.
4838 */
49- function apiKeyMetadata ( doc , ret , options ) : SanitisedApiKey {
39+ function apiKeyMetadata ( doc : any , _ret : any , _options : any ) : SanitisedApiKey {
5040 return {
5141 id : doc . id ,
5242 label : doc . label ,
@@ -63,9 +53,3 @@ apiKeySchema.set('toJSON', {
6353 virtuals : true ,
6454 transform : apiKeyMetadata
6555} ) ;
66-
67- // Derived type for schema fields (including timestamps)
68- type ApiKeySchemaType = InferSchemaType < typeof apiKeySchema > ;
69-
70- // The actual document type
71- // export type ApiKeyDocument = Document & ApiKeySchemaFields & ApiKeyVirtuals;
0 commit comments