chore(medusa): Typeorm upgrade to 0.3.11 (#3041)

This commit is contained in:
Riqwan Thamir
2023-02-15 16:25:30 +01:00
committed by GitHub
parent 8137061908
commit 121b42acfe
275 changed files with 4493 additions and 4780 deletions
@@ -1,28 +1,294 @@
import { In, Not } from "typeorm"
import { buildQuery } from "../build-query"
import { FindOptionsOrder, FindOptionsSelect, In, MoreThan, Not } from "typeorm"
import { addOrderToSelect, buildLegacyFieldsListFrom, buildQuery } from "../build-query"
describe('buildQuery', () => {
describe("buildQuery_", () => {
it("successfully creates query", () => {
const q = buildQuery(
{
id: "1234",
test1: ["123", "12", "1"],
test2: Not("this"),
},
{
relations: ["1234"],
describe("buildQuery", () => {
it("successfully creates query", () => {
const date = new Date()
const q = buildQuery(
{
id: "1234",
test1: ["123", "12", "1"],
test2: Not("this"),
date: { gt: date },
amount: { gt: 10 },
rule: {
type: "fixed"
}
)
},
{
select: [
"order",
"order.items",
"order.swaps",
"order.swaps.additional_items",
"order.discounts",
"order.discounts.rule",
"order.claims",
"order.claims.additional_items",
"additional_items",
"additional_items.variant",
"return_order",
"return_order.items",
"return_order.shipping_method",
"return_order.shipping_method.tax_lines",
],
relations: [
"order",
"order.items",
"order.swaps",
"order.swaps.additional_items",
"order.discounts",
"order.discounts.rule",
"order.claims",
"order.claims.additional_items",
"additional_items",
"additional_items.variant",
"return_order",
"return_order.items",
"return_order.shipping_method",
"return_order.shipping_method.tax_lines",
"items.variants",
"items.variants.product",
"items",
"items.tax_lines",
"items.adjustments",
],
order: {
id: "ASC",
"items.id": "ASC",
"items.variant.id": "ASC"
}
}
)
expect(q).toEqual({
where: {
id: "1234",
test1: In(["123", "12", "1"]),
test2: Not("this"),
expect(q).toEqual({
where: {
id: "1234",
test1: In(["123", "12", "1"]),
test2: Not("this"),
date: MoreThan(date),
amount: MoreThan(10),
rule: {
type: "fixed"
}
},
select: {
order: {
items: true,
swaps: {
additional_items: true,
},
discounts: {
rule: true,
},
claims: {
additional_items: true,
},
},
relations: ["1234"],
})
additional_items: {
variant: true,
},
return_order: {
items: true,
shipping_method: {
tax_lines: true,
},
},
},
relations: {
order: {
items: true,
swaps: {
additional_items: true,
},
discounts: {
rule: true,
},
claims: {
additional_items: true,
},
},
additional_items: {
variant: true,
},
return_order: {
items: true,
shipping_method: {
tax_lines: true,
},
},
items: {
variants: {
product: true
},
tax_lines: true,
adjustments: true
}
},
order: {
id: "ASC",
items: {
id: "ASC",
variant: {
id: "ASC"
}
}
}
})
})
})
})
describe("buildLegacyFieldsListFrom", () => {
it("successfully build back select object shape to list", () => {
const q = buildLegacyFieldsListFrom({
order: {
items: true,
swaps: {
additional_items: true,
},
discounts: {
rule: true,
},
claims: {
additional_items: true,
},
},
additional_items: {
variant: true,
},
return_order: {
items: true,
shipping_method: {
tax_lines: true,
},
},
})
expect(q.length).toBe(14)
expect(q).toEqual(expect.arrayContaining([
"order",
"order.items",
"order.swaps",
"order.swaps.additional_items",
"order.discounts",
"order.discounts.rule",
"order.claims",
"order.claims.additional_items",
"additional_items",
"additional_items.variant",
"return_order",
"return_order.items",
"return_order.shipping_method",
"return_order.shipping_method.tax_lines",
]))
})
it("successfully build back relation object shape to list", () => {
const q = buildLegacyFieldsListFrom({
order: {
items: true,
swaps: {
additional_items: true,
},
discounts: {
rule: true,
},
claims: {
additional_items: true,
},
},
additional_items: {
variant: true,
},
return_order: {
items: true,
shipping_method: {
tax_lines: true,
},
},
items: {
variants: {
product: true
},
tax_lines: true,
adjustments: true
}
})
expect(q.length).toBe(19)
expect(q).toEqual(expect.arrayContaining([
"order",
"order.items",
"order.swaps",
"order.swaps.additional_items",
"order.discounts",
"order.discounts.rule",
"order.claims",
"order.claims.additional_items",
"additional_items",
"additional_items.variant",
"return_order",
"return_order.items",
"return_order.shipping_method",
"return_order.shipping_method.tax_lines",
"items.variants",
"items.variants.product",
"items",
"items.tax_lines",
"items.adjustments",
]))
})
it("successfully build back order object shape to list", () => {
const q = buildLegacyFieldsListFrom({
id: "ASC",
items: {
id: "ASC",
variant: {
id: "ASC"
}
}
})
expect(q.length).toBe(5)
expect(q).toEqual(expect.arrayContaining([
"id",
"items",
"items.id",
"items.variant",
"items.variant.id"
]))
})
describe('addOrderToSelect', function () {
it("successfully add the order fields to the select object", () => {
const select: FindOptionsSelect<any> = {
item: {
variant: {
id: true
}
}
}
const order: FindOptionsOrder<any> = {
item: {
variant: {
rank: "ASC"
}
}
}
addOrderToSelect(order, select)
expect(select).toEqual({
item: {
variant: {
id: true,
rank: true
}
}
})
})
});
})
+307 -83
View File
@@ -1,10 +1,19 @@
import { ExtendedFindConfig, FindConfig } from "../types/common"
import {
ExtendedFindConfig,
FindConfig,
Selector,
Writable,
} from "../types/common"
import { FindOperator, In, IsNull, Raw } from "typeorm"
FindManyOptions,
FindOperator,
FindOptionsRelations,
FindOptionsSelect,
FindOptionsWhere,
In,
IsNull,
LessThan,
LessThanOrEqual,
MoreThan,
MoreThanOrEqual,
} from "typeorm"
import { FindOptionsOrder } from "typeorm/find-options/FindOptionsOrder"
import { isObject } from "./is-object"
/**
* Used to build TypeORM queries.
@@ -12,77 +21,12 @@ import { FindOperator, In, IsNull, Raw } from "typeorm"
* @param config The config
* @return The QueryBuilderConfig
*/
export function buildQuery<TWhereKeys, TEntity = unknown>(
export function buildQuery<TWhereKeys extends object, TEntity = unknown>(
selector: TWhereKeys,
config: FindConfig<TEntity> = {}
): ExtendedFindConfig<TEntity, TWhereKeys> {
const build = (obj: Selector<TEntity>): Partial<Writable<TWhereKeys>> => {
return Object.entries(obj).reduce((acc, [key, value]: any) => {
// Undefined values indicate that they have no significance to the query.
// If the query is looking for rows where a column is not set it should use null instead of undefined
if (typeof value === "undefined") {
return acc
}
if (value === null) {
acc[key] = IsNull()
return acc
}
const subquery: {
operator: "<" | ">" | "<=" | ">="
value: unknown
}[] = []
switch (true) {
case value instanceof FindOperator:
acc[key] = value
break
case Array.isArray(value):
acc[key] = In([...(value as unknown[])])
break
case value !== null && typeof value === "object":
Object.entries(value).map(([modifier, val]) => {
switch (modifier) {
case "lt":
subquery.push({ operator: "<", value: val })
break
case "gt":
subquery.push({ operator: ">", value: val })
break
case "lte":
subquery.push({ operator: "<=", value: val })
break
case "gte":
subquery.push({ operator: ">=", value: val })
break
default:
acc[key] = value
break
}
})
if (subquery.length) {
acc[key] = Raw(
(a) =>
subquery
.map((s, index) => `${a} ${s.operator} :${index}`)
.join(" AND "),
subquery.map((s) => s.value)
)
}
break
default:
acc[key] = value
break
}
return acc
}, {} as Partial<Writable<TWhereKeys>>)
}
const query: ExtendedFindConfig<TEntity, TWhereKeys> = {
where: build(selector),
) {
const query: ExtendedFindConfig<TEntity> = {
where: buildWhere<TWhereKeys, TEntity>(selector),
}
if ("deleted_at" in selector) {
@@ -90,24 +34,304 @@ export function buildQuery<TWhereKeys, TEntity = unknown>(
}
if ("skip" in config) {
query.skip = config.skip
;(query as FindManyOptions<TEntity>).skip = config.skip
}
if ("take" in config) {
query.take = config.take
;(query as FindManyOptions<TEntity>).take = config.take
}
if ("relations" in config) {
query.relations = config.relations
if (config.relations) {
query.relations = buildRelations<TEntity>(config.relations)
}
if ("select" in config) {
query.select = config.select
if (config.select) {
query.select = buildSelects<TEntity>(config.select as string[])
}
if ("order" in config) {
query.order = config.order
if (config.order) {
query.order = buildOrder<TEntity>(config.order)
}
return query
}
/**
* @param constraints
*
* @example
* const q = buildWhere(
* {
* id: "1234",
* test1: ["123", "12", "1"],
* test2: Not("this"),
* date: { gt: date },
* amount: { gt: 10 },
* },
*)
*
* // Output
* {
* id: "1234",
* test1: In(["123", "12", "1"]),
* test2: Not("this"),
* date: MoreThan(date),
* amount: MoreThan(10)
* }
*/
function buildWhere<TWhereKeys extends object, TEntity>(
constraints: TWhereKeys
): FindOptionsWhere<TEntity> {
const where: FindOptionsWhere<TEntity> = {}
for (const [key, value] of Object.entries(constraints)) {
if (value === undefined) {
continue
}
if (value === null) {
where[key] = IsNull()
continue
}
if (value instanceof FindOperator) {
where[key] = value
continue
}
if (Array.isArray(value)) {
where[key] = In(value)
continue
}
if (typeof value === "object") {
Object.entries(value).forEach(([objectKey, objectValue]) => {
switch (objectKey) {
case "lt":
where[key] = LessThan(objectValue)
break
case "gt":
where[key] = MoreThan(objectValue)
break
case "lte":
where[key] = LessThanOrEqual(objectValue)
break
case "gte":
where[key] = MoreThanOrEqual(objectValue)
break
default:
if (objectValue != undefined && typeof objectValue === "object") {
where[key] = buildWhere<any, TEntity>(objectValue)
return
}
where[key] = value
}
return
})
continue
}
where[key] = value
}
return where
}
/**
* Revert new object structure of find options to the legacy structure of previous version
* @example
* input: {
* test: {
* test1: true,
* test2: true,
* test3: {
* test4: true
* },
* },
* test2: true
* }
* output: ['test.test1', 'test.test2', 'test.test3.test4', 'test2']
* @param input
*/
export function buildLegacyFieldsListFrom<TEntity>(
input:
| FindOptionsWhere<TEntity>
| FindOptionsSelect<TEntity>
| FindOptionsOrder<TEntity>
| FindOptionsRelations<TEntity> = {}
): (keyof TEntity)[] {
if (!Object.keys(input).length) {
return []
}
const output: Set<string> = new Set(Object.keys(input))
for (const key of Object.keys(input)) {
if (input[key] != undefined && typeof input[key] === "object") {
const deepRes = buildLegacyFieldsListFrom(input[key])
const items = deepRes.reduce((acc, val) => {
acc.push(`${key}.${val}`)
return acc
}, [] as string[])
items.forEach((item) => output.add(item))
continue
}
output.add(key)
}
return Array.from(output) as (keyof TEntity)[]
}
export function buildSelects<TEntity>(
selectCollection: string[]
): FindOptionsSelect<TEntity> {
return buildRelationsOrSelect(selectCollection) as FindOptionsSelect<TEntity>
}
export function buildRelations<TEntity>(
relationCollection: string[]
): FindOptionsRelations<TEntity> {
return buildRelationsOrSelect(
relationCollection
) as FindOptionsRelations<TEntity>
}
export function addOrderToSelect<TEntity>(
order: FindOptionsOrder<TEntity>,
select: FindOptionsSelect<TEntity>
): void {
for (const orderBy of Object.keys(order)) {
if (isObject(order[orderBy])) {
select[orderBy] =
select[orderBy] && isObject(select[orderBy]) ? select[orderBy] : {}
addOrderToSelect(order[orderBy], select[orderBy])
continue
}
select[orderBy] = isObject(select[orderBy])
? { ...select[orderBy], id: true, [orderBy]: true }
: true
}
}
/**
* Convert an collection of dot string into a nested object
* @example
* input: [
* order,
* order.items,
* order.swaps,
* order.swaps.additional_items,
* order.discounts,
* order.discounts.rule,
* order.claims,
* order.claims.additional_items,
* additional_items,
* additional_items.variant,
* return_order,
* return_order.items,
* return_order.shipping_method,
* return_order.shipping_method.tax_lines
* ]
* output: {
* "order": {
* "items": true,
* "swaps": {
* "additional_items": true
* },
* "discounts": {
* "rule": true
* },
* "claims": {
* "additional_items": true
* }
* },
* "additional_items": {
* "variant": true
* },
* "return_order": {
* "items": true,
* "shipping_method": {
* "tax_lines": true
* }
* }
* }
* @param collection
*/
function buildRelationsOrSelect<TEntity>(
collection: string[]
): FindOptionsRelations<TEntity> | FindOptionsSelect<TEntity> {
const output: FindOptionsRelations<TEntity> | FindOptionsSelect<TEntity> = {}
for (const relation of collection) {
if (relation.indexOf(".") > -1) {
const nestedRelations = relation.split(".")
let parent = output
while (nestedRelations.length > 1) {
const nestedRelation = nestedRelations.shift() as string
parent = parent[nestedRelation] =
parent[nestedRelation] !== true &&
typeof parent[nestedRelation] === "object"
? parent[nestedRelation]
: {}
}
parent[nestedRelations[0]] = true
continue
}
output[relation] = output[relation] ?? true
}
return output
}
/**
* Convert an order of dot string into a nested object
* @example
* input: { id: "ASC", "items.title": "ASC", "items.variant.title": "ASC" }
* output: {
* "id": "ASC",
* "items": {
* "id": "ASC",
* "variant": {
* "title": "ASC"
* }
* },
* }
* @param orderBy
*/
function buildOrder<TEntity>(orderBy: {
[k: string]: "ASC" | "DESC"
}): FindOptionsOrder<TEntity> {
const output: FindOptionsOrder<TEntity> = {}
const orderKeys = Object.keys(orderBy)
for (const order of orderKeys) {
if (order.indexOf(".") > -1) {
const nestedOrder = order.split(".")
let parent = output
while (nestedOrder.length > 1) {
const nestedRelation = nestedOrder.shift() as string
parent = parent[nestedRelation] = parent[nestedRelation] ?? {}
}
parent[nestedOrder[0]] = orderBy[order]
continue
}
output[order] = orderBy[order]
}
return output
}
@@ -13,7 +13,11 @@ export type RunIdempotencyStepOptions = {
}
export async function runIdempotencyStep(
handler: ({ manager: EntityManager }) => Promise<IdempotencyCallbackResult>,
handler: ({
manager,
}: {
manager: EntityManager
}) => Promise<IdempotencyCallbackResult>,
{
manager,
idempotencyKey,
+2
View File
@@ -4,6 +4,8 @@ export * from "./validate-id"
export * from "./generate-entity-id"
export * from "./remove-undefined-properties"
export * from "./is-string"
export * from "./is-date"
export * from "./is-object"
export * from "./calculate-price-tax-amount"
export * from "./csv-cell-content-formatter"
export * from "./exception-formatter"
+4
View File
@@ -0,0 +1,4 @@
export function isDate(value: any): value is Date {
const date = new Date(value)
return !isNaN(date.valueOf())
}
+3
View File
@@ -0,0 +1,3 @@
export function isObject(obj: unknown): obj is object {
return typeof obj === "object" && !!obj
}
+14 -10
View File
@@ -1,13 +1,17 @@
// Since typeorm require us to use ES6 and that migrating require a lot of work
// one solution is to override directly the one from typeorm so that there is no complain about
// the output build
import { DefaultNamingStrategy } from "typeorm"
export class ShortenedNamingStrategy extends DefaultNamingStrategy {
eagerJoinRelationAlias(alias: string, propertyPath: string): string {
const path = propertyPath
.split(".")
.map((p) => p.substring(0, 2))
.join("_")
const out = alias + "_" + path
const match = out.match(/_/g) || []
return out + match.length
}
DefaultNamingStrategy.prototype.eagerJoinRelationAlias = function (
alias: string,
propertyPath: string
): string {
const path = propertyPath
.split(".")
.map((p) => p.substring(0, 2))
.join("_")
const out = alias + "_" + path
const match = out.match(/_/g) || []
return out + match.length
}
+10 -5
View File
@@ -1,5 +1,10 @@
import { flatten, groupBy, map, merge } from "lodash"
import { EntityMetadata, Repository, SelectQueryBuilder } from "typeorm"
import {
EntityMetadata,
ObjectLiteral,
Repository,
SelectQueryBuilder,
} from "typeorm"
import { ExtendedFindConfig } from "../types/common"
/**
@@ -12,7 +17,7 @@ import { ExtendedFindConfig } from "../types/common"
* @param select
* @param customJoinBuilders
*/
export async function queryEntityWithIds<T>(
export async function queryEntityWithIds<T extends ObjectLiteral>(
repository: Repository<T>,
entityIds: string[],
groupedRelations: { [toplevel: string]: string[] },
@@ -89,9 +94,9 @@ export async function queryEntityWithIds<T>(
* @param shouldCount
* @param customJoinBuilders
*/
export async function queryEntityWithoutRelations<T>(
export async function queryEntityWithoutRelations<T extends ObjectLiteral>(
repository: Repository<T>,
optionsWithoutRelations: Omit<ExtendedFindConfig<T, unknown>, "relations">,
optionsWithoutRelations: Omit<ExtendedFindConfig<T>, "relations">,
shouldCount = false,
customJoinBuilders: ((
qb: SelectQueryBuilder<T>,
@@ -188,7 +193,7 @@ export function mergeEntitiesWithRelations<T>(
* @param alias
* @param shouldJoin In case a join is already applied elsewhere and therefore you want to avoid to re joining the data in that case you can return false for specific relations
*/
export function applyOrdering<T>({
export function applyOrdering<T extends ObjectLiteral>({
repository,
order,
qb,