Skip to content

Commit

Permalink
chore: improved logging, cleaned up comments, added comments, removed…
Browse files Browse the repository at this point in the history
… unused apis and options.
  • Loading branch information
yusinto committed Dec 19, 2023
1 parent 42c3bc6 commit acd16db
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 86 deletions.
12 changes: 12 additions & 0 deletions packages/sdk/react-native/src/provider/LDProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ type LDProps = {
context?: LDContext;
};

/**
* This is the LaunchDarkly Provider which uses the React context api to store
* and pass data to child components through hooks.
*
* @param client The ReactNativeLDClient object. Initialize this object separately
* and then set this prop when declaring the LDProvider.
* @param context Optional. The LDContext object. If set, the LDProvider will
* `identify` this context on application mount. If not set, default flag values
* will be returned. You can run `identify` at a later time.
* @param children
* @constructor
*/
const LDProvider = ({ client, context, children }: PropsWithChildren<LDProps>) => {
const [state, setState] = useState<ReactContext>({ client });

Expand Down
7 changes: 5 additions & 2 deletions packages/shared/sdk-client/src/LDClientImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export default class LDClientImpl implements LDClient {
async close(): Promise<void> {
await this.flush();
this.eventProcessor.close();
this.streamer?.close();
}

async flush(): Promise<{ error?: Error; result: boolean }> {
Expand All @@ -113,7 +114,7 @@ export default class LDClientImpl implements LDClient {
listeners.set('put', {
deserializeData: JSON.parse,
processJson: async (dataJson: Flags) => {
this.logger.debug(`Streamer PUT: ${JSON.stringify(dataJson, null, 2)}`);
this.logger.debug(`Streamer PUT: ${dataJson})}`);
if (initializedFromStorage) {
this.logger.debug('Synchronizing all data');
const changeset: LDFlagChangeset = {};
Expand Down Expand Up @@ -282,7 +283,7 @@ export default class LDClientImpl implements LDClient {
return p;
}

off(eventName: EventName, listener?: Function): void {
off(eventName: EventName, listener: Function): void {
this.emitter.off(eventName, listener);
}

Expand Down Expand Up @@ -327,6 +328,7 @@ export default class LDClientImpl implements LDClient {
const error = new LDClientError(
`Unknown feature flag "${flagKey}"; returning default value ${defVal}`,
);
this.logger.error(error);
this.emitter.emit('error', this.context, error);
this.eventProcessor.sendEvent(
this.eventFactoryDefault.unknownFlagEvent(flagKey, defVal, evalContext),
Expand All @@ -352,6 +354,7 @@ export default class LDClientImpl implements LDClient {
const error = new LDClientError(
`Wrong type "${type}" for feature flag "${flagKey}"; returning default value`,
);
this.logger.error(error);
this.emitter.emit('error', this.context, error);
return createErrorEvaluationDetail(ErrorKinds.WrongType, defaultValue);
}
Expand Down
55 changes: 21 additions & 34 deletions packages/shared/sdk-client/src/api/LDClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface LDClient {
* @returns
* An object in which each key is a feature flag key and each value is the flag value.
* Note that there is no way to specify a default value for each flag as there is with
* {@link variation}, so any flag that cannot be evaluated will have a null value.
* {@link variation}, so any flag that cannot be evaluated will be undefined.
*/
allFlags(): LDFlagSet;

Expand All @@ -39,7 +39,7 @@ export interface LDClient {
boolVariation(key: string, defaultValue: boolean): boolean;

/**
* Determines the boolean variation of a feature flag for a context, along with information about
* Determines the boolean variation of a feature flag, along with information about
* how it was calculated.
*
* The `reason` property of the result will also be included in analytics events, if you are
Expand Down Expand Up @@ -82,27 +82,26 @@ export interface LDClient {
* Returns the client's current context.
*
* This is the context that was most recently passed to {@link identify}, or, if {@link identify} has never
* been called, the initial context specified when the client was created.
* been called, this will be undefined.
*/
getContext(): LDContext | undefined;

/**
* Identifies a context to LaunchDarkly.
*
* Unlike the server-side SDKs, the client-side JavaScript SDKs maintain a current context state,
* which is set at initialization time. You only need to call `identify()` if the context has changed
* since then.
* which is set when you call `identify()`.
*
* Changing the current context also causes all feature flag values to be reloaded. Until that has
* finished, calls to {@link variation} will still return flag values for the previous context. You can
* use a callback or a Promise to determine when the new flag values are available.
* await the Promise to determine when the new flag values are available.
*
* @param context
* The context properties. Must contain at least the `key` property.
* The LDContext object.
* @param hash
* The signed context key if you are using [Secure Mode](https://docs.launchdarkly.com/sdk/features/secure-mode#configuring-secure-mode-in-the-javascript-client-side-sdk).
* @returns
* A Promise which resolve once the flag values for the new context are available.
* A Promise which resolves when the flag values for the specified context are available.
*/
identify(context: LDContext, hash?: string): Promise<void>;

Expand All @@ -121,7 +120,7 @@ export interface LDClient {
jsonVariation(key: string, defaultValue: unknown): unknown;

/**
* Determines the json variation of a feature flag for a context, along with information about how it
* Determines the json variation of a feature flag, along with information about how it
* was calculated.
*
* The `reason` property of the result will also be included in analytics events, if you are
Expand All @@ -137,8 +136,7 @@ export interface LDClient {
* @param defaultValue The default value of the flag, to be used if the value is not available
* from LaunchDarkly.
* @returns
* If you provided a callback, then nothing. Otherwise, a Promise which will be resolved with
* the result (as an{@link LDEvaluationDetailTyped<unknown>}).
* The result (as an {@link LDEvaluationDetailTyped<unknown>}).
*/
jsonVariationDetail(key: string, defaultValue: unknown): LDEvaluationDetailTyped<unknown>;

Expand Down Expand Up @@ -184,16 +182,14 @@ export interface LDClient {
numberVariationDetail(key: string, defaultValue: number): LDEvaluationDetailTyped<number>;

/**
* Deregisters an event listener. See {@link on} for the available event types.
* Removes an event listener. See {@link on} for the available event types.
*
* @param key
* The name of the event for which to stop listening.
* @param callback
* The function to deregister.
* @param context
* The `this` context for the callback, if one was specified for {@link on}.
*/
off(key: string, callback: (...args: any[]) => void, context?: any): void;
off(key: string, callback: (...args: any[]) => void): void;

/**
* Registers an event listener.
Expand All @@ -215,25 +211,14 @@ export interface LDClient {
* because you have switched contexts with {@link identify}, or because the client has a
* stream connection and has received a live change to a flag value (see below).
* The callback parameter is an {@link LDFlagChangeset}.
* - `"change:FLAG-KEY"`: The client has received a new value for a specific flag
* whose key is `FLAG-KEY`. The callback receives two parameters: the current (new)
* flag value, and the previous value. This is always accompanied by a general
* `"change"` event as described above; you can listen for either or both.
*
* The `"change"` and `"change:FLAG-KEY"` events have special behavior: by default, the
* client will open a streaming connection to receive live changes if and only if
* you are listening for one of these events. This behavior can be overridden by
* setting `streaming` in {@link LDOptions} or calling {@link LDClient.setStreaming}.
*
* @param key
* The name of the event for which to listen.
* @param callback
* The function to execute when the event fires. The callback may or may not
* receive parameters, depending on the type of event.
* @param context
* The `this` context to use for the callback.
*/
on(key: string, callback: (...args: any[]) => void, context?: any): void;
on(key: string, callback: (...args: any[]) => void): void;

/**
* Determines the string variation of a feature flag.
Expand Down Expand Up @@ -270,14 +255,10 @@ export interface LDClient {
stringVariationDetail(key: string, defaultValue: string): LDEvaluationDetailTyped<string>;

/**
* Track page events to use in goals or A/B tests.
*
* LaunchDarkly automatically tracks pageviews and clicks that are specified in the
* Goals section of their dashboard. This can be used to track custom goals or other
* events that do not currently have goals.
* Track events for experiments.
*
* @param key
* The name of the event, which may correspond to a goal in A/B tests.
* The name of the event, which may correspond to a goal in an experiment.
* @param data
* Additional information to associate with the event.
* @param metricValue
Expand All @@ -289,7 +270,10 @@ export interface LDClient {
track(key: string, data?: any, metricValue?: number): void;

/**
* Determines the variation of a feature flag for the current context.
* We recommend using strongly typed variation methods which perform
* type checks and handle type errors.
*
* Determines the variation of a feature flag.
*
* In the client-side JavaScript SDKs, this is always a fast synchronous operation because all of
* the feature flag values for the current context have already been loaded into memory.
Expand All @@ -304,6 +288,9 @@ export interface LDClient {
variation(key: string, defaultValue?: LDFlagValue): LDFlagValue;

/**
* We recommend using strongly typed variation detail methods which perform
* type checks and handle type errors.
*
* Determines the variation of a feature flag for a context, along with information about how it was
* calculated.
*
Expand Down
46 changes: 0 additions & 46 deletions packages/shared/sdk-client/src/api/LDOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,52 +44,6 @@ export interface LDOptions {
*/
streamUri?: string;

/**
* Whether or not to open a streaming connection to LaunchDarkly for live flag updates.
*
* If this is true, the client will always attempt to maintain a streaming connection; if false,
* it never will. If you leave the value undefined (the default), the client will open a streaming
* connection if you subscribe to `"change"` or `"change:flag-key"` events (see {@link LDClient.on}).
*
* This is equivalent to calling `client.setStreaming()` with the same value.
*/
stream?: boolean;

/**
* Whether or not to use the REPORT verb to fetch flag settings.
*
* If this is true, flag settings will be fetched with a REPORT request
* including a JSON entity body with the context object.
*
* Otherwise (by default) a GET request will be issued with the context passed as
* a base64 uri-encoded path parameter.
*
* Do not use unless advised by LaunchDarkly.
*/
useReport?: boolean;

/**
* Whether or not to include custom HTTP headers when requesting flags from LaunchDarkly.
*
* These are used to send metadata about the SDK (such as the version). They
* are also used to send the application.id and application.version set in
* the options.
*
* This defaults to true (custom headers will be sent). One reason you might
* want to set it to false is that the presence of custom headers causes
* browsers to make an extra OPTIONS request (a CORS preflight check) before
* each flag request, which could affect performance.
*/
sendLDHeaders?: boolean;

/**
* A transform function for dynamic configuration of HTTP headers.
*
* This method will run last in the header generation sequence, so the function should have
* all system generated headers in case those also need to be modified.
*/
requestHeaderTransform?: (headers: Map<string, string>) => Map<string, string>;

/**
* Whether LaunchDarkly should provide additional information about how flag values were
* calculated.
Expand Down
4 changes: 0 additions & 4 deletions packages/shared/sdk-client/src/configuration/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ const validators: Record<keyof LDOptions, TypeValidator> = {
diagnosticOptOut: TypeValidators.Boolean,
withReasons: TypeValidators.Boolean,
sendEvents: TypeValidators.Boolean,
sendLDHeaders: TypeValidators.Boolean,
useReport: TypeValidators.Boolean,

inspectors: TypeValidators.createTypeArray<LDInspection>('LDInspection[]', {
type: 'flag-used',
Expand All @@ -41,8 +39,6 @@ const validators: Record<keyof LDOptions, TypeValidator> = {

application: TypeValidators.Object,
bootstrap: new BootStrapValidator(),
requestHeaderTransform: TypeValidators.Function,
stream: TypeValidators.NullableBoolean,
wrapperName: TypeValidators.String,
wrapperVersion: TypeValidators.String,
hash: TypeValidators.String,
Expand Down

0 comments on commit acd16db

Please sign in to comment.