UNPKG

iopa

Version:

API-first, Internet of Things (IoT) stack for Typescript, official implementation of the Internet Open Protocols Alliance (IOPA) reference pattern

88 lines (76 loc) 2.4 kB
/* * Internet Open Protocol Abstraction (IOPA) * Copyright (c) 2016-2022 Internet Open Protocols Alliance * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { IContextIopa, IContextIopaLegacy, IFactory, IReplyIopa } from '@iopa/types' import FreeList from '../util/freelist' import Factory from './factory-core' import { ContextEdge, ContextReply } from './context-edge' /** Represents IopaContext Factory of up to 100 items */ export default class FactoryEdge< C, T extends IContextIopa<C> & { init: Function; dispose?: Function } > extends Factory<C, T> implements IFactory<C, T> { protected _factoryResponse: FreeList<IReplyIopa> public constructor( name: string = 'IopaContext', size: number = 100, factory: () => T = () => new ContextEdge() as any ) { super(name, size, factory) this._factoryResponse = new FreeList( 'IopaReply', size, () => new ContextReply() ) } /** Creates a new IOPA Context */ public createContext( urlOrRequest?: string | Request, options?: Partial<IContextIopaLegacy<C>> ): T { const context = super.createContext(urlOrRequest, options) const response: IReplyIopa = this._factoryResponse.alloc().init() context.response = response return context as T } /** Release the memory used by a given IOPA Context */ protected _dispose( context: T & IContextIopa<C> & { init: Function; dispose?: Function } ): void { if (context === null || context.get('server.AbortController') === null) { return } if (context.response) { const { response } = context Object.keys(response).forEach((prop) => { response[prop] = null }) this._factoryResponse.free(response) } Object.keys(context).forEach((prop) => { context[prop] = null }) this._factory.free(context) } }