typeorm#getConnection TypeScript Examples

The following examples show how to use typeorm#getConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiMetaController.ts    From Designer-Server with GNU General Public License v3.0 6 votes vote down vote up
/**
   * meta의 목록
   * @param request 
   * @param page 
   * @param perPage 
   */
  @Get("/")
  @Security("jwt")
  public async getIndex(
    @Request() request: exRequest,
    @Query('page') page?: number,
    @Query('perPage') perPage?: number
  ):Promise<Pagination<Meta>>{
    const pagination = new Pagination(Meta, getConnection());
    const relations = ["stage", "stage.application"];
    await pagination.findBySearchParams(relations, page, perPage, request.user.id);
    return Promise.resolve(pagination);
  }
Example #2
Source File: discipline.routes.ts    From Typescript_TypeORM with Apache License 2.0 6 votes vote down vote up
disciplineRouter.post('/', async (request, response) => {
  try {
    const repo = getRepository(Discipline);
    const res = await repo.save(request.body);
    await getConnection().queryResultCache?.remove(['listDiscipline']);
    return response.status(201).json(res);
  } catch (err) {
    console.log('err.message :>> ', err.message);
    return response.status(400).send();
  }
});
Example #3
Source File: backfill-site-data.ts    From aqualink-app with MIT License 6 votes vote down vote up
async function run(siteId: number, days: number) {
  const backlogArray = Array.from(Array(days).keys());
  const today = moment()
    .utc()
    .hours(23)
    .minutes(59)
    .seconds(59)
    .milliseconds(999);

  // eslint-disable-next-line fp/no-mutating-methods
  await Bluebird.mapSeries(backlogArray.reverse(), async (past) => {
    const date = moment(today);
    date.day(today.day() - past - 1);
    try {
      await getSitesDailyData(getConnection(), date.toDate(), [siteId]);
    } catch (error) {
      logger.error(error);
    }
  });
}
Example #4
Source File: post.ts    From lireddit with MIT License 6 votes vote down vote up
@Mutation(() => Post, { nullable: true })
  @UseMiddleware(isAuth)
  async updatePost(
    @Arg("id", () => Int) id: number,
    @Arg("title") title: string,
    @Arg("text") text: string,
    @Ctx() { req }: MyContext
  ): Promise<Post | null> {
    const result = await getConnection()
      .createQueryBuilder()
      .update(Post)
      .set({ title, text })
      .where('id = :id and "creatorId" = :creatorId', {
        id,
        creatorId: req.session.userId,
      })
      .returning("*")
      .execute();

    return result.raw[0];
  }
Example #5
Source File: getUser.ts    From vsinder with Apache License 2.0 6 votes vote down vote up
getUser = (userId: string) =>
  getConnection()
    .query(
      `select (u."pushToken" is not null or u."pushToken" != '') "hasPushToken",
      COALESCE("location", '') "location", ${quotedMeFields},
  array(select json_build_object('userId1', m."userId1", 'userId1', m."userId2")
    from match m
    where (m."userId1" = $2 and read1 = false)
    or (m."userId2" = $3 and read2 = false)
    ) "unreadMatchUserIds"
  from "user" u where id = $1 limit 1`,
      [userId, userId, userId]
    )
    .then((x) => x[0])
Example #6
Source File: getUser.ts    From vsinder-api with Apache License 2.0 6 votes vote down vote up
getUser = (userId: string) =>
  getConnection()
    .query(
      `select (u."pushToken" is not null or u."pushToken" != '') "hasPushToken",
      COALESCE("location", '') "location", ${quotedMeFields},
  array(select json_build_object('userId1', m."userId1", 'userId1', m."userId2")
    from match m
    where (m."userId1" = $2 and read1 = false)
    or (m."userId2" = $3 and read2 = false)
    ) "unreadMatchUserIds"
  from "user" u where id = $1 limit 1`,
      [userId, userId, userId]
    )
    .then((x) => x[0])
Example #7
Source File: prepareData.ts    From typeorm-cursor-pagination with MIT License 6 votes vote down vote up
export async function prepareData(): Promise<void> {
  const data = [...Array(10).keys()].map((i) => ({
    name: `user${i}`,
    balance: balances[i],
    camelCaseColumn: setTimestamp(i),
    photos: [
      {
        link: `http://photo.com/${i}`,
      },
    ],
  }));

  await getConnection()
    .getRepository(User)
    .save(data);
}
Example #8
Source File: ChatRoom.resolver.ts    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
@Mutation(() => Boolean)
  async createChatRoom(@Arg('data') data: ChatRoomCreateInput) {
    const queryBuilder = await getConnection()
      .createQueryBuilder()
      .insert()
      .into(ChatRoomEntity)
      .values([data])
      .execute();

    console.log(queryBuilder);

    return true;
  }
Example #9
Source File: UserAccount.ts    From Wern-Fullstack-Template with MIT License 6 votes vote down vote up
@Mutation(() => UserResponse)
  async createUser(@Arg('options') options: UserInput): Promise<UserResponse> {
    const errors = validateRegister(options)
    if (errors) {
      return { errors }
    }

    const hashedPassword = await argon2.hash(options.password)
    let user
    try {
      const result = await getConnection()
        .createQueryBuilder()
        .insert()
        .into(UserAccount)
        .values({
          username: options.username,
          email: options.email,
          password: hashedPassword,
        })
        .returning('*')
        .execute()
      user = result.raw[0]
    } catch (err) {
      if (err.code === '23505') {
        return {
          errors: [
            {
              field: 'username',
              message: 'username already taken',
            },
          ],
        }
      }
    }

    return { user }
  }
Example #10
Source File: index.ts    From backend with MIT License 6 votes vote down vote up
async function initModule() {
    try {
        const conn = getConnection();

        let x = await conn.query("SELECT wix_creation_date AS latest_date FROM (" +
            "(SELECT wix_creation_date FROM pupil ORDER BY wix_creation_date DESC LIMIT 1) " +
            "UNION " +
            "(SELECT wix_creation_date FROM student ORDER BY wix_creation_date DESC LIMIT 1)" +
            ") t ORDER BY latest_date DESC LIMIT 1;");

        if (x.length == 0) {
            lastFetch = new Date();
            logger.warn("Can't get date of last fetch. Using now as last fetch date.");
        } else {
            lastFetch = new Date(x[0].latest_date);
            logger.info("Restored old last fetch date: ", lastFetch);
        }

        init = true;
    } catch (e) {
        logger.error("Can't initialize fetch module: ", e.message);
        logger.debug(e);
    }
}
Example #11
Source File: healthz.ts    From fosscord-server with GNU Affero General Public License v3.0 6 votes vote down vote up
router.get("/", route({}), (req: Request, res: Response) => {
	try {
		// test that the database is alive & responding
		getConnection();
		return res.sendStatus(200);
	} catch (e) {
		res.sendStatus(503);
	}
});
Example #12
Source File: controller.ts    From backend-postgres-typescript-node-express with MIT License 6 votes vote down vote up
list = async (req: Request, res: Response, next: NextFunction): Promise<any> => {
  try {
    const users = await getConnection()
      .getRepository(User)
      .createQueryBuilder('user')
      .getMany()

    return res.status(200).send(users)
  } catch (error) {
    return res.status(500).send(error)
  }
}
Example #13
Source File: test-utils.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
closeDBAfterTest = async (): Promise<void> => {
  console.log(`Closing connection to ${TEST_DB_NAME} database`);
  const connection = await getConnection(TEST_DB_CONNECTION_NAME);

  await connection.close();
}
Example #14
Source File: connection.spec.ts    From advanced-node with GNU General Public License v3.0 6 votes vote down vote up
jest.mock('typeorm', () => ({
  Entity: jest.fn(),
  PrimaryGeneratedColumn: jest.fn(),
  Column: jest.fn(),
  createConnection: jest.fn(),
  getConnection: jest.fn(),
  getConnectionManager: jest.fn(),
  getRepository: jest.fn()
}))
Example #15
Source File: index.ts    From type-graphql-dataloader with MIT License 6 votes vote down vote up
export async function listen(
  port: number,
  resolvers: NonEmptyArray<Function>
): Promise<ListenResult> {
  const app = express();

  const schema = await buildSchema({
    resolvers,
  });

  const apollo = new ApolloServer({
    schema,
    plugins: [
      ApolloServerLoaderPlugin({
        typeormGetConnection: getConnection,
      }),
    ],
  });
  await apollo.start();

  apollo.applyMiddleware({ app, cors: false });

  const server = http.createServer(app);
  await promisify(server.listen.bind(server, port))();

  return {
    port: (server.address() as AddressInfo).port,
    close: promisify(server.close).bind(server),
  };
}
Example #16
Source File: jwt.middleware.ts    From bulwark with MIT License 6 votes vote down vote up
isAdmin = async (req, res, next) => {
  const user = await getConnection()
    .getRepository(User)
    .createQueryBuilder('user')
    .leftJoinAndSelect('user.teams', 'teams')
    .where('user.id = :userId', { userId: req.user })
    .getOne();
  if (user.teams.some((team) => team.role === ROLE.ADMIN)) {
    next();
  } else {
    return res.status(403).json('Authorization is required');
  }
}
Example #17
Source File: dal.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
export function getIndexerHead(): Promise<number> {
  // serialization failures are possible, but let's assume they are rare
  return getConnection().transaction('SERIALIZABLE', async (em) => {
    const raw = (await em.query(`
      SELECT height FROM status WHERE id = 0
    `)) as { height: number }[]

    assert.strictEqual(raw.length, 1, 'There must be exactly one status record')

    const height = raw[0].height

    const higherBlocks = (await em.query(
      'SELECT height FROM substrate_block WHERE height > $1 ORDER BY height ASC',
      [height]
    )) as { height: number }[]

    let actualHeight = height
    for (let i = 0; i < higherBlocks.length; i++) {
      const bh = higherBlocks[i].height
      if (bh === actualHeight + 1) {
        actualHeight = bh
      }
    }

    if (actualHeight > height) {
      await em.query('UPDATE status SET height = $1 WHERE id = 0', [
        actualHeight,
      ])
    }

    if (actualHeight === -1 || actualHeight < conf().BLOCK_HEIGHT) {
      return conf().BLOCK_HEIGHT - 1
    } else {
      return Number(actualHeight)
    }
  })
}
Example #18
Source File: db.ts    From node-typescript-starter-kit with MIT License 6 votes vote down vote up
DBConnect = async () => {
  let connection: Connection | undefined;
  try {
    connection = getConnection();
  } catch (e) {
  }

  try {
    if (connection) {
      if (!connection.isConnected) {
        await connection.connect();
      }
    } else {
      await createConnection(ORMConfig);
    }
    console.log("? Database connection was successful!");
  } catch (e) {
    console.error('ERROR: Database connection failed!!', e);
    throw e;
  }
}
Example #19
Source File: login.ts    From TypeScript-Login-Register with MIT License 5 votes vote down vote up
alt.onClient(
  "client::lr:loginAccount",
  async (player: alt.Player, data: ILoginAccountData) => {
    try {
      data.socialId = player.socialId;
      const loginConnection = getConnection("lr");
      const result = await loginConnection
        .createQueryBuilder(Account, "account")
        .leftJoinAndSelect("account.validation", "validation")
        .where("account.username = :username", { username: data.username })
        .getOne();
      if (!result) {
        let err: IErrorMessage = {
          location: "login",
          param: "username",
          msg: "The given username does not exist",
        };
        return alt.emitClient(player, "server::lr:showLoginError", err);
      }

      let passwordResult: boolean = await compare(
        data.password,
        result.password
      );

      if (!passwordResult) {
        let err: IErrorMessage = {
          location: "login",
          param: "password",
          msg: "The given password is incorrect",
        };
        return alt.emitClient(player, "server::lr:showLoginError", err);
      }

      if (data.socialClub != result.validation.scNickname) {
        let err: IErrorMessage = {
          location: "login",
          param: "scNickname",
          msg:
            "Your socialclub name diffes from the one, you registred with, please use your old account to login",
        };
        return alt.emitClient(player, "server::lr:showLoginError", err);
      }

      if (data.socialId != result.validation.socialId) {
        let err: IErrorMessage = {
          location: "login",
          param: "socialId",
          msg:
            "Your socialclub id diffes from the one, you registred with, please use your old account to login",
        };
        return alt.emitClient(player, "server::lr:showLoginError", err);
      }

      const loginData: ILoginAccountData = {
        socialClub: result.validation.scNickname,
        username: result.username,
        discordUserID: result.validation.discordUserID,
      };

      player.setSyncedMeta("userData", loginData);

      alt.emitClient(player, "client:lr:loginSuccessfull");
    } catch (error) {
      alt.log(error);
      let err: IErrorMessage = {
        location: "server",
        param: "",
        msg: "Internal server error, please try again later",
      };
      return alt.emitClient(player, "server::lr:showLoginError", err);
    }
  }
);
Example #20
Source File: base.repository.ts    From Cromwell with MIT License 5 votes vote down vote up
constructor(
        private EntityClass: (new (...args: any[]) => EntityType & { id?: number }),
    ) {
        super();
        this.dbType = getStoreItem('dbInfo')?.dbType as ConnectionOptions['type']
            ?? getConnection().options.type;
    }