Skip to content

Commit

Permalink
fix: sort imports by first member
Browse files Browse the repository at this point in the history
  • Loading branch information
rintoj committed Jun 7, 2024
1 parent dbe17ca commit 8770cef
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/gql/gql-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -589,17 +589,22 @@ export function organizeImports(sourceFile: ts.SourceFile): ts.SourceFile {
return statement
})

const sortedFileNames = Object.keys(importStatements)
.filter(fromFile => !!importStatements[fromFile].size)
.map(from => ({ from, firstImport: Array.from(importStatements[from]).sort()[0] }))
.sort((a, b) => a.firstImport.localeCompare(b.firstImport))
.map(item => item.from)

return {
...sourceFile,
statements: [
...Object.keys(importStatements)
.filter(fromFile => !importStatements[fromFile].size)
.sort()
.map(fromFile => createImport(fromFile, ...Array.from(importStatements[fromFile]).sort())),
...Object.keys(importStatements)
.filter(fromFile => !!importStatements[fromFile].size)
.sort()
.map(fromFile => createImport(fromFile, ...Array.from(importStatements[fromFile]).sort())),
...sortedFileNames.map(fromFile =>
createImport(fromFile, ...Array.from(importStatements[fromFile]).sort()),
),
...sourceFile.statements.filter(statement => !ts.isImportDeclaration(statement)),
] as any,
}
Expand Down
27 changes: 27 additions & 0 deletions src/gql/organize-import.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { toParsedOutput } from '../util/test-util'
import { parseTS, printTS, prettify } from '../util/ts-util'
import { organizeImports } from './gql-util'

describe('organizeImport', () => {
test('to organize imports', async () => {
const sourceFile = parseTS(`
import { FieldResolver } from '../../common/field-resolver-type'
import { GQLContext } from '../../context'
import { ReturnService } from '../return/return.service'
import { Shipment } from './shipment.model'
import { ShipmentType, TransactionStatus } from './shipment.type'
import { Context, Parent, ResolveField, Resolver } from '@nestjs/graphql'
`)
const code = await prettify(printTS(organizeImports(sourceFile)))
expect(toParsedOutput(code)).toEqual(
toParsedOutput(`
import { Context, Parent, ResolveField, Resolver } from '@nestjs/graphql'
import { FieldResolver } from '../../common/field-resolver-type'
import { GQLContext } from '../../context'
import { ReturnService } from '../return/return.service'
import { Shipment } from './shipment.model'
import { ShipmentType, TransactionStatus } from './shipment.type'
`),
)
})
})

0 comments on commit 8770cef

Please sign in to comment.