Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: option to sort URL parameters alphabetically #387

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ The following options can be used when creating an instance of `ImgixClient`:
- **`includeLibraryParam`:** Boolean. Specifies whether the constructed URLs will include an [`ixlib` parameter](#what-is-the-ixlib-param-on-every-request). Defaults to `true`.
- **`secureURLToken`:** String. When specified, this token will be used to sign images. Read more about securing images [on the imgix Docs site](https://docs.imgix.com/setup/securing-images). Defaults to `null`.
- :warning: *The `secureURLToken` option should only be used in server-side applications to prevent exposing your secure token.* :warning:
- **`sortParams`:** Boolean. Specifies whether the constructed URLs parameters should be sorted alphabetically. Defaults to `false`.


## API
Expand Down
1 change: 1 addition & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ export const DEFAULT_OPTIONS = {
includeLibraryParam: true,
urlPrefix: 'https://',
secureURLToken: null,
sortParams: false,
};
57 changes: 30 additions & 27 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,27 +108,39 @@ export default class ImgixClient {
const useCustomEncoder = !!options.encoder;
const customEncoder = options.encoder;

const queryParams = [
let queryParams = [
// Set the libraryParam if applicable.
...(this.settings.libraryParam
? [`ixlib=${this.settings.libraryParam}`]
? [['ixlib', this.settings.libraryParam]]
: []),
...Object.entries(params),
];

// Map over the key-value pairs in params while applying applicable encoding.
...Object.entries(params).reduce((prev, [key, value]) => {
if (value == null) {
return prev;
}
const encodedKey = useCustomEncoder ? customEncoder(key, value) : encodeURIComponent(key);
const encodedValue =
key.substr(-2) === '64'
? useCustomEncoder ? customEncoder(value, key) : Base64.encodeURI(value)
: useCustomEncoder ? customEncoder(value, key) : encodeURIComponent(value);
prev.push(`${encodedKey}=${encodedValue}`);
if (this.settings.sortParams) {
queryParams = queryParams.sort(([a], [b]) =>
a > b ? 1 : a < b ? -1 : 0,
);
}

// Map over the key-value pairs in params while applying applicable encoding.
queryParams = queryParams.reduce((prev, [key, value]) => {
if (value == null) {
return prev;
}, []),
];
}

const encodedKey = useCustomEncoder
? customEncoder(key, value)
: encodeURIComponent(key);
const encodedValue = useCustomEncoder
? customEncoder(value, key)
: key.substr(-2) === '64'
? Base64.encodeURI(value)
: encodeURIComponent(value);

prev.push(`${encodedKey}=${encodedValue}`);

return prev;
}, []);

return `${queryParams.length > 0 ? '?' : ''}${queryParams.join('&')}`;
}
Expand All @@ -152,7 +164,7 @@ export default class ImgixClient {
* @param {boolean} options.encode Whether to encode the path, default true
* @returns {string} The sanitized path
*/
_sanitizePath(path, options = {}) {
_sanitizePath(path, options = {}) {
// Strip leading slash first (we'll re-add after encoding)
let _path = path.replace(/^\//, '');

Expand Down Expand Up @@ -289,12 +301,7 @@ export default class ImgixClient {
}

const srcset = targetWidthValues.map(
(w) =>
`${this.buildURL(
path,
{ ...params, w },
options,
)} ${w}w`,
(w) => `${this.buildURL(path, { ...params, w }, options)} ${w}w`,
);

return srcset.join(',\n');
Expand Down Expand Up @@ -334,11 +341,7 @@ export default class ImgixClient {
const srcset = disableVariableQuality
? targetRatios.map(
(dpr) =>
`${this.buildURL(
path,
{ ...params, dpr },
options,
)} ${dpr}x`,
`${this.buildURL(path, { ...params, dpr }, options)} ${dpr}x`,
)
: targetRatios.map((dpr) => withQuality(path, params, dpr));

Expand Down
27 changes: 24 additions & 3 deletions test/test-buildURL.js
Original file line number Diff line number Diff line change
Expand Up @@ -396,11 +396,11 @@ describe('URL Builder:', function describeSuite() {
{
encoder: (path) => encodeURI(path).replace("'", "%27")
}
)
);

const expected = 'https://test.imgix.net/unsplash/walrus.jpg?txt=test!(%27)&txt-color=000&txt-size=400&txt-font=Avenir-Black&txt-x=800&txt-y=600'
const expected = 'https://test.imgix.net/unsplash/walrus.jpg?txt=test!(%27)&txt-color=000&txt-size=400&txt-font=Avenir-Black&txt-x=800&txt-y=600';

assert.strictEqual(actual, expected)
assert.strictEqual(actual, expected);
});

it('can custom encode the parameter value based on the parameter key', () => {
Expand All @@ -410,5 +410,26 @@ describe('URL Builder:', function describeSuite() {

assert.strictEqual(result, expectation);
});

it('sorts parameters if the `sortParams` setting is truthy', () => {
client.settings.sortParams = true;

const actual = client.buildURL(
"unsplash/walrus.jpg",
{
txt64: 'base64',
txt: 'text',
'txt-color': '000',
'txt-size': 400,
'txt-x': 800,
'txt-y': 600,
'txt-font': 'Avenir-Black',
}
);

const expected = 'https://test.imgix.net/unsplash/walrus.jpg?txt=text&txt-color=000&txt-font=Avenir-Black&txt-size=400&txt-x=800&txt-y=600&txt64=YmFzZTY0';

assert.strictEqual(actual, expected);
});
});
});
7 changes: 4 additions & 3 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ declare class ImgixClient {
secureURLToken?: string;
useHTTPS?: boolean;
includeLibraryParam?: boolean;
sortParams?: boolean;
});

buildURL(
Expand Down Expand Up @@ -53,12 +54,12 @@ export interface SrcSetOptions {
}

export interface _sanitizePathOptions {
disablePathEncoding?: boolean,
encoder?: (path: string) => string
disablePathEncoding?: boolean;
encoder?: (path: string) => string;
}

export interface _buildParamsOptions {
encoder?: (value: string, key?: string) => string
encoder?: (value: string, key?: string) => string;
}

export default ImgixClient;