UNPKG

@aws-amplify/core

Version:
65 lines (62 loc) 2.48 kB
import { AmplifyClass } from '../../singleton/Amplify.mjs'; import { AmplifyServerContextError } from '../error/AmplifyServerContextError.mjs'; import { serverContextRegistry } from './serverContextRegistry.mjs'; // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 /** * Creates an Amplify server context. * @param amplifyConfig The Amplify resource config. * @param libraryOptions The Amplify library options. * @returns The Amplify server context spec. */ const createAmplifyServerContext = (amplifyConfig, libraryOptions) => { const amplify = new AmplifyClass(); amplify.configure(amplifyConfig, libraryOptions); return serverContextRegistry.register({ amplify, }); }; /** * Returns an Amplify server context. * @param contextSpec The context spec used to get the Amplify server context. * @returns The Amplify server context. */ const getAmplifyServerContext = (contextSpec) => { assertContextSpec(contextSpec); const context = serverContextRegistry.get(contextSpec); if (context) { return context; } throw new AmplifyServerContextError({ message: 'Attempted to get the Amplify Server Context that may have been destroyed.', recoverySuggestion: 'Ensure always call Amplify APIs within `runWithAmplifyServerContext` function, and do not attempt to reuse `contextSpec` object.', }); }; /** * Destroys an Amplify server context. * @param contextSpec The context spec used to destroy the Amplify server context. */ const destroyAmplifyServerContext = (contextSpec) => { serverContextRegistry.deregister(contextSpec); }; const assertContextSpec = (contextSpec) => { let invalid = false; if (!Object.prototype.hasOwnProperty.call(contextSpec, 'token')) { invalid = true; } else if (!Object.prototype.hasOwnProperty.call(contextSpec.token, 'value')) { invalid = true; } else if (Object.prototype.toString.call(contextSpec.token.value) !== '[object Symbol]') { invalid = true; } if (invalid) { throw new AmplifyServerContextError({ message: 'Invalid `contextSpec`.', recoverySuggestion: 'Ensure to use the `contextSpec` object injected by `runWithAmplifyServerContext` function.', }); } }; export { createAmplifyServerContext, destroyAmplifyServerContext, getAmplifyServerContext }; //# sourceMappingURL=serverContext.mjs.map