Skip to content

Commit

Permalink
fix: update rext client and publish targets (#355)
Browse files Browse the repository at this point in the history
* fix(rext-client): fix query params handler to handre arrays

* fix: add publish target to schematics package

* fix: update @tractr/hapify-update-templates-import-path and fix publish target (#350)
  • Loading branch information
maxmousse committed Jan 7, 2022
1 parent 3119cde commit 72346a2
Show file tree
Hide file tree
Showing 21 changed files with 378 additions and 144 deletions.
9 changes: 7 additions & 2 deletions apps/api/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ async function bootstrap() {
const port = process.env.PORT || 3000;
const globalPrefix = 'api';

// Instanciate nest app
// Instantiate nest app
const app = await NestFactory.create(AppModule);

// Set custom logger service
Expand All @@ -23,7 +23,12 @@ async function bootstrap() {

app.use(morgan('combined'));

app.use(cookieParser('myScret'));
const { COOKIE_SECRET: cookieSecret } = process.env;

if (cookieSecret === undefined || cookieSecret === '')
throw new Error('COOKIE_SECRET is missing in the environment variables');

app.use(cookieParser(cookieSecret));

// Set global validation pipe
app.useGlobalPipes(
Expand Down
1 change: 1 addition & 0 deletions libs/common/src/lib/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './get-concat-value-by-path.helper';
export * from './is-class.helper';
export * from './unique-array.helper';
export * from './url.helper';
107 changes: 107 additions & 0 deletions libs/common/src/lib/helpers/url.helper.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { formatQueryParameters, getUrl } from './url.helper';

describe('Url helpers', () => {
describe('formateQueryParameters', () => {
it('should stringify items in arrays', () => {
const queryParams = {
array: ['10', 10, false, { test: 'test' }],
};

const expectedResult =
'array[]=10&array[]=10&array[]=false&array[]=%7B%22test%22%3A%22test%22%7D';

const result = formatQueryParameters(queryParams);

expect(result).toEqual(expectedResult);
});

it('should stringify dates', () => {
const date = new Date('August 19, 1975 23:15:30 GMT-3:00');

const queryParams = {
date,
};

const expectedResult = 'date=1975-08-20T02%3A15%3A30.000Z';
const result = formatQueryParameters(queryParams);

expect(result).toEqual(expectedResult);
});

it('should stringify objects', () => {
const queryParams = {
object: { test: 'foo' },
};

const expectedResult = 'object=%7B%22test%22%3A%22foo%22%7D';

const result = formatQueryParameters(queryParams);

expect(result).toEqual(expectedResult);
});

it('should ignore empty strings and undefined values and keep null', () => {
const queryParams = {
emptyString: '',
nonDefined: undefined,
nullish: null,
};

const expectedResult = 'nullish=null';

const result = formatQueryParameters(queryParams);

expect(result).toEqual(expectedResult);
});

it('should return valid queryParams', () => {
const date = new Date('August 19, 1975 23:15:30 GMT-3:00');

const queryParams = {
nonDefined: undefined,
nullish: null,
array: ['item1', 'item2'],
boolean: true,
date,
number: 100,
object: { test: 'foo' },
objectArray: [{ test1: 'foo' }, { test2: 'foo' }],
string: 'string',
};

const expectedResult =
'array[]=item1&array[]=item2&boolean=true&date=1975-08-20T02%3A15%3A30.000Z&nullish=null&number=100&object=%7B%22test%22%3A%22foo%22%7D&objectArray[]=%7B%22test1%22%3A%22foo%22%7D&objectArray[]=%7B%22test2%22%3A%22foo%22%7D&string=string';

const result = formatQueryParameters(queryParams);

expect(result).toEqual(expectedResult);
});
});

describe('getUrl', () => {
it('should build a correct url', () => {
const baseUrl = new URL('https://base.com');
const parameters = '/users';

const date = new Date('August 19, 1975 23:15:30 GMT-3:00');
const queryParams = {
nonDefined: undefined,
nullish: null,
array: ['item1', 'item2'],
boolean: true,
date,
number: 100,
object: { test: 'foo' },
objectArray: [{ test1: 'foo' }, { test2: 'foo' }],
string: 'string',
};

const expectedResult =
'https://base.com/users?array[]=item1&array[]=item2&boolean=true&date=1975-08-20T02%3A15%3A30.000Z&nullish=null&number=100&object=%7B%22test%22%3A%22foo%22%7D&objectArray[]=%7B%22test1%22%3A%22foo%22%7D&objectArray[]=%7B%22test2%22%3A%22foo%22%7D&string=string';

const result = getUrl(baseUrl, parameters, queryParams).toString();

expect(result).toBe(expectedResult);
});
});
});
63 changes: 63 additions & 0 deletions libs/common/src/lib/helpers/url.helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as queryString from 'query-string';

/**
* Format a query parameters object into a query parameters string
* @param queryParams - Object to format
* @returns a query parameters string
*/
export function formatQueryParameters(queryParams: Record<string, any>) {
const formattedQueryParams = Object.entries(queryParams).reduce(
(acc, [key, value]) => {
// for values of type array, items that are of type object are stringified
if (Array.isArray(value)) {
acc[key] = value.map((item) =>
typeof item === 'object' ? JSON.stringify(item) : item,
);

// Dates must be stringified
} else if (value instanceof Date) {
acc[key] = value.toISOString();

// Objects must be stringified
} else if (typeof value === 'object') {
acc[key] = JSON.stringify(value);

// Other types of values does no require any process
} else {
acc[key] = value;
}

return acc;
},
{} as Record<string, any>,
);

return queryString.stringify(formattedQueryParams, {
arrayFormat: 'bracket',
skipNull: false,
skipEmptyString: true,
});
}

/**
* Build a correctly formatted url from a base url,
* url parameters and query parameters
*
* @param baseUrl - Base of the url (protocol and domain)
* @param parameters - Url parameters
* @param queryParams - Url query parameters
* @returns a correctly formatted url
*/
export function getUrl(
baseUrl: URL,
parameters = '',
queryParams: Record<string, any> = {},
): URL {
const url = new URL(
`${baseUrl.pathname.replace(/\/$/, '')}${parameters}`,
baseUrl,
);
url.search = formatQueryParameters(queryParams);
return url;
}
5 changes: 0 additions & 5 deletions libs/generated/hapify.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,6 @@
"engine": "hpf",
"input": "all"
},
{
"path": "generated/rext-client/helpers/url.ts",
"engine": "hpf",
"input": "all"
},
{
"path": "generated/rext-client/helpers/universal-rxjs-ajax.ts",
"engine": "hpf",
Expand Down
5 changes: 0 additions & 5 deletions libs/hapify/templates/rext-client/.hapifyrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@ module.exports = {
engine: 'hpf',
input: 'all',
},
{
path: 'generated/rext-client/helpers/url.ts',
engine: 'hpf',
input: 'all',
},
{
path: 'generated/rext-client/helpers/universal-rxjs-ajax.ts',
engine: 'hpf',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './rest-ajax';
export * from './transform-and-validate';
export * from './url';

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Observable, OperatorFunction } from 'rxjs';
import { AjaxConfig, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';

import { getUrl, URLSearchParamsType } from './url';
import { getUrl } from '@tractr/common';
import { request } from './universal-rxjs-ajax';

export function ajax<T>(
Expand Down Expand Up @@ -62,7 +62,7 @@ export type CountAjaxOptions = Omit<
* @param options - Ajax request options
* @returns the number of Model
*/
export function count<CountQuery extends URLSearchParamsType>(
export function count<CountQuery extends Record<string, any>>(
apiUrl: URL,
countQuery: CountQuery,
options: CountAjaxOptions = {},
Expand Down Expand Up @@ -93,7 +93,7 @@ export type FindUniqueOptions = Omit<
export function findUnique<
T,
FindUniqueParams extends { id: string | number },
FindUniqueQuery extends URLSearchParamsType,
FindUniqueQuery extends Record<string, any>,
>(
apiUrl: URL,
findUniqueParams: FindUniqueParams,
Expand Down Expand Up @@ -122,7 +122,7 @@ export type FindManyOptions = Omit<
* @param options - Ajax request options
* @returns an array of Model entities
*/
export function findMany<T, FindManyQuery extends URLSearchParamsType>(
export function findMany<T, FindManyQuery extends Record<string, any>>(
apiUrl: URL,
findManyQuery: FindManyQuery,
options: FindManyOptions = {},
Expand Down

This file was deleted.

4 changes: 2 additions & 2 deletions libs/hapify/update-templates-import-path/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@tractr/update-templates-import-path",
"name": "@tractr/hapify-update-templates-import-path",
"version": "1.31.0",
"description": "Generate hapify config",
"description": "Update relative path in code generated by hapify",
"repository": {
"type": "git",
"url": "https://github.com/tractr/stack"
Expand Down
6 changes: 5 additions & 1 deletion libs/schematics/src/executors/generate/executor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,17 @@ import executor from './executor';
import { GenerateExecutorSchema } from './schema';

import * as hapifyGenerateConfig from '@tractr/hapify-generate-config';
import * as hapifyUpdateTemplates from '@tractr/update-templates-import-path';
import * as hapifyUpdateTemplates from '@tractr/hapify-update-templates-import-path';

jest.mock('child_process');
jest.mock('@tractr/hapify-generate-config', () => ({
__esModule: true,
...jest.requireActual('@tractr/hapify-generate-config'),
}));
jest.mock('@tractr/hapify-update-templates-import-path', () => ({
__esModule: true,
...jest.requireActual('@tractr/hapify-update-templates-import-path'),
}));

describe('Generate executor:generate', () => {
let defaultContext: ExecutorContext;
Expand Down
Loading

0 comments on commit 72346a2

Please sign in to comment.