Skip to content

Commit

Permalink
DVC-5923 Rename environmentKey to sdkKey to be consistent across SDKs (
Browse files Browse the repository at this point in the history
…#408)

* Rename environmentKey to sdkKey to be consistant across SDKs

* cleanup readme.md
  • Loading branch information
jonathannorris authored Feb 17, 2023
1 parent e397225 commit d83d9de
Show file tree
Hide file tree
Showing 17 changed files with 67 additions and 68 deletions.
2 changes: 1 addition & 1 deletion examples/react/react-native-app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pod install

## Running the example

* In `App.tsx`, set `SDK_KEY` to the Environment Key.
* In `App.tsx`, set `SDK_KEY` to the SDK Key for your environment.
You can find this under Settings / Environments on the DevCycle dashboard.
* Create a new feature on the dashboard. Update the `VARIABLE_KEY` in `App.tsx` to this value.
* If you added user targeting to your feature, update the `user_id` field in `App.tsx` based on your targeting rules.
Expand Down
2 changes: 1 addition & 1 deletion examples/react/with-async-provider/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Install all packages using `yarn` in the root directory.

## Running the example

* In `index.tsx`, set `SDK_KEY` to the Environment Key.
* In `index.tsx`, set `SDK_KEY` to the SDK Key for your environment.
You can find this under Settings / Environments on the DevCycle dashboard.
* Create a new feature on the dashboard. Update the `variableKey` in `DevCycleExample.tsx` to this value.
* If you added user targeting to your feature, update the `user_id` field in `index.tsx` based on your targeting rules.
Expand Down
2 changes: 1 addition & 1 deletion examples/react/with-provider/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Install all packages using `yarn` in the root directory.

## Running the example

* In `App.tsx`, set `SDK_KEY` to the Environment Key.
* In `App.tsx`, set `SDK_KEY` to the SDK Key for your environment.
You can find this under Settings / Environments on the DevCycle dashboard.
* Create a new feature on the dashboard. Update the `variableKey` in `DevCycleExample.tsx` to this value.
* If you added user targeting to your feature, update the `user_id` field in `App.tsx` based on your targeting rules.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { jsonArrFromValueArray } from '../helpers/jsonHelpers'
import { _getClientCustomData } from './clientCustomDataManager'

/**
* Map<environmentKey, EventQueue>
* Map<sdkKey, EventQueue>
*/
const _eventQueueMap = new Map<string, EventQueue>()

Expand Down
28 changes: 14 additions & 14 deletions sdk/js/__tests__/Request.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,26 +30,26 @@ describe('Request tests', () => {

describe('baseRequestParams', () => {
const { baseRequestHeaders } = Request
it('should add environmentKey header if passed in', () => {
it('should add sdkKey header if passed in', () => {
const params = baseRequestHeaders('my_sdk_key')
expect(params['Content-Type']).toBe('application/json')
expect(params['Authorization']).toBe('my_sdk_key')
})

it('should not add header if no environmentKey passed in', () => {
it('should not add header if no sdkKey passed in', () => {
const params = baseRequestHeaders()
expect(params['Content-Type']).toBe('application/json')
expect(params['Authorization']).toBeUndefined()
})
})

describe('getConfigJson', () => {
it('should call get with serialized user and environment key in params', async () => {
it('should call get with serialized user and SDK key in params', async () => {
const user = { user_id: 'my_user', isAnonymous: false }
const environmentKey = 'my_sdk_key'
const sdkKey = 'my_sdk_key'
axiosRequestMock.mockResolvedValue({ status: 200, data: {} })

await Request.getConfigJson(environmentKey, user as DVCPopulatedUser, defaultLogger, {}, {
await Request.getConfigJson(sdkKey, user as DVCPopulatedUser, defaultLogger, {}, {
sse: true,
lastModified: 1234
})
Expand All @@ -58,37 +58,37 @@ describe('Request tests', () => {
headers: { 'Content-Type': 'application/json' },
method: 'GET',
url: 'https://sdk-api.devcycle.com/v1/sdkConfig?sdkKey=' +
`${environmentKey}&user_id=${user.user_id}&isAnonymous=false&sse=1&sseLastModified=1234`
`${sdkKey}&user_id=${user.user_id}&isAnonymous=false&sse=1&sseLastModified=1234`
})
})

it('should call local proxy for apiProxyURL option', async () => {
const user = { user_id: 'my_user', isAnonymous: false }
const environmentKey = 'my_sdk_key'
const sdkKey = 'my_sdk_key'
const dvcOptions = { apiProxyURL: 'http://localhost:4000' }
axiosRequestMock.mockResolvedValue({ status: 200, data: {} })

await Request.getConfigJson(environmentKey, user as DVCPopulatedUser, defaultLogger, dvcOptions)
await Request.getConfigJson(sdkKey, user as DVCPopulatedUser, defaultLogger, dvcOptions)

expect(axiosRequestMock).toBeCalledWith({
headers: { 'Content-Type': 'application/json' },
method: 'GET',
url: `${dvcOptions.apiProxyURL}/v1/sdkConfig?sdkKey=` +
`${environmentKey}&user_id=${user.user_id}&isAnonymous=false`
`${sdkKey}&user_id=${user.user_id}&isAnonymous=false`
})
})
})

describe('publishEvents', () => {

it('should call get with serialized user and environment key in params', async () => {
it('should call get with serialized user and SDK key in params', async () => {
const user = { user_id: 'my_user' } as DVCPopulatedUser
const config = {} as BucketedUserConfig
const environmentKey = 'my_sdk_key'
const sdkKey = 'my_sdk_key'
const events = [{ type: 'event_1_type' }, { type: 'event_2_type' }]
axiosRequestMock.mockResolvedValue({ status: 200, data: 'messages' })

await Request.publishEvents(environmentKey, config, user, events, defaultLogger)
await Request.publishEvents(sdkKey, config, user, events, defaultLogger)

expect(axiosRequestMock).toBeCalledWith({
headers: {
Expand Down Expand Up @@ -121,10 +121,10 @@ describe('Request tests', () => {
describe('saveEntity', () => {
it('should send user data to edgedb api with url-encoded id', async () => {
const user = { user_id: 'user@example.com', isAnonymous: false }
const environmentKey = 'my_sdk_key'
const sdkKey = 'my_sdk_key'
axiosRequestMock.mockResolvedValue({ status: 200, data: {} })

await Request.saveEntity(user as DVCPopulatedUser, environmentKey, defaultLogger)
await Request.saveEntity(user as DVCPopulatedUser, sdkKey, defaultLogger)

expect(axiosRequestMock).toBeCalledWith({
headers: {
Expand Down
4 changes: 2 additions & 2 deletions sdk/js/__tests__/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jest.spyOn(Request, 'getConfigJson').mockImplementation(() => {
return Promise.resolve({})
})

const missingKeyError = 'Missing environment key! Call initialize with a valid environment key'
const missingKeyError = 'Missing SDK key! Call initialize with a valid SDK key'
const missingUserError = 'Missing user! Call initialize with a valid user'
const invalidUserError = 'Must have a user_id, or have "isAnonymous" set on the user'
const invalidOptionsError = 'Invalid options! Call initialize with valid options'
Expand All @@ -18,7 +18,7 @@ describe('initialize tests', () => {
expect(client).not.toBeNull()
})

it('should throw an error if environment key is not passed in initialize', () => {
it('should throw an error if SDK key is not passed in initialize', () => {
expect(() => DVCClient.initialize('')).toThrow(missingKeyError)
expect(() => DVCClient.initialize()).toThrow(missingKeyError)
})
Expand Down
13 changes: 6 additions & 7 deletions sdk/js/src/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@ import { ConfigRequestConsolidator } from './ConfigRequestConsolidator'
import { dvcDefaultLogger } from './logger'
import { DVCLogger } from '@devcycle/types'
import { StreamingConnection } from './StreamingConnection'
import DefaultCacheStore from './DefaultCacheStore'

export class DVCClient implements Client {
private options: DVCOptions
private onInitialized: Promise<DVCClient>
private variableDefaultMap: { [key: string]: { [key: string]: DVCVariable<any> } }
private environmentKey: string
private sdkKey: string
private userSaved = false
private _closing = false
private isConfigCached = false
Expand All @@ -48,17 +47,17 @@ export class DVCClient implements Client {
private inactivityHandlerId?: number
private windowMessageHandler?: (event: MessageEvent) => void

constructor(environmentKey: string, user: DVCUser, options: DVCOptions = {}) {
constructor(sdkKey: string, user: DVCUser, options: DVCOptions = {}) {
this.logger = options.logger || dvcDefaultLogger({ level: options.logLevel })
this.store = new CacheStore(
options.storage || new DefaultStorage(), this.logger
)

this.options = options

this.environmentKey = environmentKey
this.sdkKey = sdkKey
this.variableDefaultMap = {}
this.eventQueue = new EventQueue(environmentKey, this, options?.eventFlushIntervalMS)
this.eventQueue = new EventQueue(sdkKey, this, options?.eventFlushIntervalMS)

this.eventEmitter = new EventEmitter()
this.registerVisibilityChangeHandler()
Expand All @@ -67,7 +66,7 @@ export class DVCClient implements Client {
this.user = new DVCPopulatedUser(user, options, undefined, storedAnonymousId)
this.requestConsolidator = new ConfigRequestConsolidator(
(user: DVCPopulatedUser, extraParams) => getConfigJson(
this.environmentKey, user, this.logger, this.options, extraParams
this.sdkKey, user, this.logger, this.options, extraParams
),
(config: BucketedUserConfig, user: DVCPopulatedUser) =>
this.handleConfigReceived(config, user, Date.now()),
Expand Down Expand Up @@ -320,7 +319,7 @@ export class DVCClient implements Client {
this.store.saveUser(user)

if (!this.user.isAnonymous && checkIfEdgeEnabled(config, this.logger, this.options?.enableEdgeDB, true)) {
saveEntity(this.user, this.environmentKey, this.logger, this.options)
saveEntity(this.user, this.sdkKey, this.logger, this.options)
.then((res) => this.logger.info(`Saved response entity! ${res}`))
}

Expand Down
8 changes: 4 additions & 4 deletions sdk/js/src/EventQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ type AggregateEvent = DVCEvent & {
}

export class EventQueue {
private readonly environmentKey: string
private readonly sdkKey: string
client: DVCClient
eventQueue: DVCEvent[]
aggregateEventMap: Record<string, Record<string, AggregateEvent>>
eventFlushIntervalMS: number
flushInterval: ReturnType<typeof setInterval>

constructor(environmentKey: string, dvcClient: DVCClient, eventFlushIntervalMS?: number) {
this.environmentKey = environmentKey
constructor(sdkKey: string, dvcClient: DVCClient, eventFlushIntervalMS?: number) {
this.sdkKey = sdkKey
this.client = dvcClient
this.eventQueue = []
this.aggregateEventMap = {}
Expand All @@ -46,7 +46,7 @@ export class EventQueue {

try {
const res = await publishEvents(
this.environmentKey,
this.sdkKey,
this.client.config || null,
this.client.user,
eventsToFlush,
Expand Down
16 changes: 8 additions & 8 deletions sdk/js/src/Request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ export const CONFIG_PATH = '/v1/sdkConfig'
export const EVENTS_PATH = '/v1/events'
export const SAVE_ENTITY_PATH = '/v1/edgedb'

export const baseRequestHeaders = (environmentKey?: string): AxiosRequestHeaders => {
export const baseRequestHeaders = (sdkKey?: string): AxiosRequestHeaders => {
return {
'Content-Type': 'application/json',
...(environmentKey ? { 'Authorization': environmentKey } : {})
...(sdkKey ? { 'Authorization': sdkKey } : {})
}
}

Expand All @@ -47,35 +47,35 @@ export const get = async (url: string): Promise<AxiosResponse> => {

export const post = async (
url: string,
environmentKey: string,
sdkKey: string,
body: Record<string, unknown>
): Promise<AxiosResponse> => {
return await axiosClient.request({
method: 'POST',
url,
data: body,
headers: baseRequestHeaders(environmentKey)
headers: baseRequestHeaders(sdkKey)
})
}

export const patch = async (
url: string,
environmentKey: string,
sdkKey: string,
body: Record<string, unknown>
): Promise<AxiosResponse> => {
return await axiosClient.request({
method: 'PATCH',
url,
data: body,
headers: baseRequestHeaders(environmentKey)
headers: baseRequestHeaders(sdkKey)
})
}

/**
* Endpoints
*/
export const getConfigJson = async (
environmentKey: string,
sdkKey: string,
user: DVCPopulatedUser,
logger: DVCLogger,
options?: DVCOptions,
Expand All @@ -86,7 +86,7 @@ export const getConfigJson = async (
const lastModified = extraParams?.lastModified ? `&sseLastModified=${extraParams.lastModified}` : ''
const queryParams = `${serializeUser(user)}${edgeDBParam}${sseParam}${lastModified}`
const url = `${options?.apiProxyURL || CLIENT_SDK_URL}${CONFIG_PATH}` +
`?sdkKey=${environmentKey}${queryParams && '&' + queryParams}`
`?sdkKey=${sdkKey}${queryParams && '&' + queryParams}`

try {
const res = await get(url)
Expand Down
8 changes: 4 additions & 4 deletions sdk/js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { DVCClient } from './Client'

export * from './types'

export const initialize = (environmentKey: string, user: DVCUser, options: DVCOptions = {}): DVCClient => {
export const initialize = (sdkKey: string, user: DVCUser, options: DVCOptions = {}): DVCClient => {
// TODO: implement logger
if (typeof window === 'undefined') {
console.warn('Window is not defined, try initializing in a browser context')
Expand All @@ -22,8 +22,8 @@ export const initialize = (environmentKey: string, user: DVCUser, options: DVCOp
'Import react-native-device-info and set global.DeviceInfo when running on React Native')
}

if (!environmentKey) {
throw new Error('Missing environment key! Call initialize with a valid environment key')
if (!sdkKey) {
throw new Error('Missing SDK key! Call initialize with a valid SDK key')
}

if (!user) {
Expand All @@ -34,7 +34,7 @@ export const initialize = (environmentKey: string, user: DVCUser, options: DVCOp
throw new Error('Invalid options! Call initialize with valid options')
}

const client = new DVCClient(environmentKey, user, options)
const client = new DVCClient(sdkKey, user, options)

client.onClientInitialized()
.then(() => client.logger.info('Successfully initialized DevCycle!'))
Expand Down
4 changes: 2 additions & 2 deletions sdk/js/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ export type DVCFeatureSet = {

/**
* Initialize the SDK
* @param environmentKey
* @param sdkKey
* @param user
* @param options
*/
export type initialize = (
environmentKey: string,
sdkKey: string,
user: DVCUser,
options?: DVCOptions
) => DVCClient
Expand Down
6 changes: 3 additions & 3 deletions sdk/nodejs/__tests__/initialize.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ describe('NodeJS SDK Initialize', () => {
it('fails to initialize in Local Bucketing mode when no token is provided', () => {
expect(() =>
initialize(undefined as unknown as string)
).toThrow('Missing environment key! Call initialize with a valid environment key')
).toThrow('Missing SDK key! Call initialize with a valid SDK key')
})

it('fails to initialize in Local Bucketing mode when client token is provided', () => {
expect(() =>
initialize('dvc_client_token')
).toThrow('Invalid environment key provided. Please call initialize with a valid server environment key')
).toThrow('Invalid SDK key provided. Please call initialize with a valid server SDK key')
})

it('sucessfully calls initialize with enableCloudBucketing set to true', () => {
Expand All @@ -33,6 +33,6 @@ describe('NodeJS SDK Initialize', () => {
it('fails to initialize in Cloud Bucketing mode when no token is provided', () => {
expect(() =>
initialize(undefined as unknown as string, { enableCloudBucketing: true })
).toThrow('Missing environment key! Call initialize with a valid environment key')
).toThrow('Missing SDK key! Call initialize with a valid SDK key')
})
})
Loading

4 comments on commit d83d9de

@vercel
Copy link

@vercel vercel bot commented on d83d9de Feb 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on d83d9de Feb 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on d83d9de Feb 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on d83d9de Feb 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

js-sdks-next-js – ./

dvc-nextjs.vercel.app
js-sdks-next-js-taplytics.vercel.app
js-sdks-next-js-git-main-taplytics.vercel.app

Please sign in to comment.