Skip to content

Commit

Permalink
wait database is ready by simple code way
Browse files Browse the repository at this point in the history
  • Loading branch information
denakol committed Aug 31, 2020
1 parent db6fca9 commit 551745b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 11 deletions.
31 changes: 31 additions & 0 deletions api/src/createFirstConnection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Connection } from 'typeorm/connection/Connection'
import { createConnection } from 'typeorm'

async function createFirstConnection(): Promise<{
connection: Connection | null
exception?: Error
}> {
let i = 20
let lastException = null
while (i > 0) {
try {
return { connection: await createConnection() }
} catch (ex) {
lastException = ex
i--
}
await sleep(5000)
}
return {
connection: null,
exception: lastException,
}
}

function sleep(ms: number) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}

export { createFirstConnection }
13 changes: 6 additions & 7 deletions api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { ApolloServer, makeExecutableSchema } from 'apollo-server'

import 'reflect-metadata'
import { createConnection } from 'typeorm'
import schemaDefs from './schema/index'
import resolvers from './resolvers'
import { Context } from './context'
import { createFirstConnection } from './createFirstConnection'

const startServer = async () => {
const resolversAny: any = resolvers
Expand All @@ -13,16 +12,16 @@ const startServer = async () => {
resolvers: resolversAny,
})

try {
const connection = await createConnection()
const result = await createFirstConnection()
if (result.connection) {
const server = new ApolloServer({
schema,
context: new Context(connection),
context: new Context(result.connection),
})

server.listen({ port: 4000 }, () => console.log(`🚀 Server ready at http://localhost:4000`))
} catch (ex) {
console.log(`Can't connect to database`, ex)
} else {
console.log(`Can't connect to database`, result.exception)
}
}

Expand Down
4 changes: 0 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ services:
build: './web'
links:
- api
depends_on:
- api
ports:
- "3000:3000"
env_file:
Expand All @@ -16,8 +14,6 @@ services:
build: './api'
links:
- db
depends_on:
- db
ports:
- "4000:4000"
volumes:
Expand Down

0 comments on commit 551745b

Please sign in to comment.