console#assert TypeScript Examples

The following examples show how to use console#assert. 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: rinkeby.ts    From arbitrum-dai-bridge with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function getRinkebyNetworkConfig({
  pkey,
  l1Rpc,
  l2Rpc,
}: {
  pkey: string
  l1Rpc: string
  l2Rpc: string
}): Promise<NetworkConfig> {
  const l1 = new ethers.providers.JsonRpcProvider(l1Rpc)
  const l2 = new RetryProvider(5, l2Rpc) // arbitrum l2 testnet is very unstable so we use RetryProvider
  const l1Deployer = new ethers.Wallet(pkey, l1)
  const l2Deployer = new ethers.Wallet(pkey, l2)

  assert((await l1.getNetwork()).chainId === 4, 'Not rinkeby!')
  assert((await l2.getNetwork()).chainId === 421611, 'Not arbitrum testnet!')

  return {
    l1: {
      provider: l1,
      deployer: l1Deployer,
      dai: '0xd9e66A2f546880EA4d800F189d6F12Cc15Bff281', // our own deployment
      inbox: '0x578BAde599406A8fE3d24Fd7f7211c0911F5B29e',
      makerPauseProxy: '0x00edb63bc6f36a45fc18c98e03ad2d707652ab5c', // dummy EOA controlled by us
      makerESM: ethers.constants.AddressZero,
    },
    l2: {
      provider: l2,
      deployer: l2Deployer,
    },
  }
}
Example #2
Source File: authentication.ts    From backend with MIT License 6 votes vote down vote up
@Authorized(Role.USER)
    @Mutation(returns => Boolean)
    logout(@Ctx() context: GraphQLContext) {
        ensureSession(context);
        const logger = logInContext(`GraphQL Authentication`, context);


        if (!context.user) {
            throw new ForbiddenError("User already logged out");
        }

        const deleted = userSessions.delete(context.sessionToken);
        assert(deleted, "User session is successfully deleted");

        context.user = undefined;
        logger.info(`Successfully logged out`);

        return true;
    }
Example #3
Source File: index.ts    From backend with MIT License 6 votes vote down vote up
/**
 * @api {GET} /certificates
 * @apiVersion 1.1.0
 * @apiDescription
 * View certificate data
 *
 * Returns data for certificates requested by the user or to be approved by the user (either student = user or pupil = user)
 *
 *
 * @apiName getCertificates
 * @apiGroup Certificate
 *
 * @apiExample {curl} Curl
 * curl -k -i -X GET https://api.corona-school.de/api/certificates
 *
 * @apiUse StatusUnauthorized
 * @apiUse StatusInternalServerError
 *
 * @typedef {Object} Response
 * @property {Array} certificates
 *
 * @returns {Response}
 */
export async function getCertificatesEndpoint(req: Request, res: Response) {
    assert(res.locals.user, "No user set");


    try {
        const certificates = await getCertificatesFor(res.locals.user);
        return res.json({ certificates });
    } catch (error) {
        logger.error("Retrieving certificates for user failed with", error);
        return res.status(500).send("Internal Server error");
    }
}
Example #4
Source File: mockedDatastore.ts    From AIPerf with MIT License 6 votes vote down vote up
async storeMetricData(trialJobId: string, data: string): Promise<void> {
        const metrics = JSON.parse(data) as MetricData;
        assert(trialJobId === metrics.trial_job_id);
        await this.dbMetrics.saveData({
            trialJobId: metrics.trial_job_id,
            parameterId: metrics.parameter_id,
            type: metrics.type,
            data: metrics.value,
            timestamp: Date.now()
        });
    }
Example #5
Source File: app.ts    From vscode-rss with MIT License 6 votes vote down vote up
async rss_import_from_opml(account: Account) {
        const collection = this.collections[account.key] as LocalCollection;
        assert(collection.type === 'local');
        const paths = await vscode.window.showOpenDialog({canSelectMany: false});
        if (!paths) {
            return;
        }

        const xml = await readFile(paths[0].fsPath);
        const dom = parser.parse(xml, {
            attributeNamePrefix: "",
            ignoreAttributes: false,
            parseAttributeValue: true,
        });

        const walk = (node: any, feeds: string[]) => {
            if (node?.xmlUrl) {
                feeds.push(node.xmlUrl as string);
            }
            if (node?.outline) {
                for (const outline of node.outline) {
                    walk(outline, feeds);
                }
            }
            return feeds;
        };

        await collection.addFeeds(walk(dom.opml?.body, []));
    }
Example #6
Source File: mainnet.ts    From arbitrum-dai-bridge with GNU Affero General Public License v3.0 6 votes vote down vote up
// maker contracts: https://changelog.makerdao.com/releases/mainnet/1.9.5/contracts.json
// arbitrum contracts: https://github.com/OffchainLabs/arbitrum/blob/master/packages/arb-bridge-eth/_deployments/1_current_deployment.json

export async function getMainnetNetworkConfig({
  pkey,
  l1Rpc,
  l2Rpc,
}: {
  pkey: string
  l1Rpc: string
  l2Rpc: string
}): Promise<NetworkConfig> {
  const l1 = new ethers.providers.JsonRpcProvider(l1Rpc)
  const l2 = new RetryProvider(5, l2Rpc) // arbitrum l2 can be very unstable so we use RetryProvider
  const l1Deployer = new ethers.Wallet(pkey, l1)
  const l2Deployer = new ethers.Wallet(pkey, l2)

  assert((await l1.getNetwork()).chainId === 1, 'Not mainnet!')
  assert((await l2.getNetwork()).chainId === 42161, 'Not arbitrum one!')

  return {
    l1: {
      provider: l1,
      deployer: l1Deployer,
      dai: '0x6B175474E89094C44Da98b954EedeAC495271d0F',
      inbox: '0x4Dbd4fc535Ac27206064B68FfCf827b0A60BAB3f',
      makerPauseProxy: '0xBE8E3e3618f7474F8cB1d074A26afFef007E98FB',
      makerESM: '0x29CfBd381043D00a98fD9904a431015Fef07af2f',
    },
    l2: {
      provider: l2,
      deployer: l2Deployer,
    },
  }
}
Example #7
Source File: verify-local.ts    From airnode with MIT License 6 votes vote down vote up
async function main() {
  for (const contractName of contractNames) {
    const deployment = await hre.deployments.get(contractName);
    const artifact = await hre.deployments.getArtifact(contractName);

    const creationTx = await hre.ethers.provider.getTransaction(deployment.transactionHash);
    // Verify that the creation tx hash belongs to the address
    assert(creationTx.creates === deployment.address);
    const creationData = creationTx.data;

    // Check if the calldata in the creation tx matches with the local build
    const constructor = artifact.abi.find((method: any) => method.type === 'constructor');
    if (constructor) {
      // If a constructor is defined, encode and add the constructor arguments to the contract bytecode
      const constructorArgumentTypes = constructor.inputs.map((input: any) => input.type);
      const encodedConstructorArguments = hre.ethers.utils.defaultAbiCoder.encode(
        constructorArgumentTypes,
        deployment.args
      );
      const generatedCreationData = hre.ethers.utils.solidityPack(
        ['bytes', 'bytes'],
        [artifact.bytecode, encodedConstructorArguments]
      );
      if (creationData !== generatedCreationData) {
        throw new Error(`${contractName} deployment on ${hre.network.name} DOES NOT match the local build!`);
      }
    } else {
      if (creationData !== artifact.bytecode) {
        throw new Error(`${contractName} deployment on ${hre.network.name} DOES NOT match the local build!`);
      }
    }
    logger.log(`${contractName} deployment on ${hre.network.name} matches the local build!`);
  }
}
Example #8
Source File: AeadAes128Gcm.ts    From SkeldJS with GNU General Public License v3.0 6 votes vote down vote up
static multiplyGf128Elements(x: Buffer, y: Buffer, scratchZ: Buffer, scratchV: Buffer) {
        assert(x.byteLength === 16);
        assert(y.byteLength === 16);
        assert(scratchZ.byteLength === 16);
        assert(scratchV.byteLength === 16);

        scratchZ.fill(0);
        x.copy(scratchV);

        for (let i = 0; i < 128; ++i) {
            const bitIdx = 7 - (i % 8);
            if ((y[Math.floor(i / 8)] & (1 << bitIdx)) > 0) {
                for (let j = 0; j < 16; ++j) {
                    scratchZ[j] ^= scratchV[j];
                }
            }

            let carry = false;
            for (let j = 0; j < 16; ++j) {
                const newCarry = (scratchV[j] & 0x1) > 0;
                scratchV[j] >>= 1;
                if (carry) {
                    scratchV[j] |= 0x80;
                }
                carry = newCarry;
            }
            if (carry) {
                scratchV[0] ^= 0xe1;
            }
        }

        scratchZ.copy(x);
    }
Example #9
Source File: AeadAes128Gcm.ts    From SkeldJS with GNU General Public License v3.0 6 votes vote down vote up
ghash(output: Buffer, data: Buffer, numBlocks: number) {
        assert(output.byteLength === 16);
        assert(data.byteLength >= numBlocks * 16);

        let readIdx = 0;
        for (let i = 0; i < numBlocks; ++i) {
            for (let j = 0; j < 16; ++j, ++readIdx) {
                output[j] ^= data[readIdx];
            }

            Aes128Gcm.multiplyGf128Elements(output, this.hashSubKey, this.blockZ, this.blockV);
        }
    }
Example #10
Source File: AeadAes128Gcm.ts    From SkeldJS with GNU General Public License v3.0 6 votes vote down vote up
gctr(output: Buffer, counterBlock: Buffer, counter: number, data: Buffer) {
        assert(counterBlock.byteLength === 16);
        assert(output.byteLength >= data.byteLength);

        let writeIdx = 0;
        const numBlocks = Math.floor((data.byteLength + 15) / 16);
        for (let i = 0; i < numBlocks; ++i) {
            counterBlock.writeInt32BE(counter, 12);
            counter++;
            this.cipher.update(counterBlock).copy(this.blockScratch);

            for (let j = 0; j < 16 && writeIdx < data.byteLength; ++j, ++writeIdx) {
                output[writeIdx] = data[writeIdx] ^ this.blockScratch[j];
            }
        }
    }
Example #11
Source File: AeadAes128Gcm.ts    From SkeldJS with GNU General Public License v3.0 6 votes vote down vote up
generateAuthTag(output: Buffer, ciphertext: Buffer, associatedData: Buffer) {
        assert(output.byteLength >= Aes128Gcm.TagSize);

        this.blockS.fill(0);

        let fullBlocks = Math.floor(associatedData.byteLength / 16);
        this.ghash(this.blockS, associatedData, fullBlocks);
        if (fullBlocks * 16 < associatedData.byteLength) {
            this.blockScratch.fill(0);
            associatedData.copy(this.blockScratch, 0, fullBlocks * 16);
            this.ghash(this.blockS, this.blockScratch, 1);
        }

        fullBlocks = Math.floor(ciphertext.byteLength / 16);
        this.ghash(this.blockS, ciphertext, fullBlocks);
        if (fullBlocks * 16 < ciphertext.byteLength) {
            this.blockScratch.fill(0);
            ciphertext.copy(this.blockScratch, 0, fullBlocks * 16);
            this.ghash(this.blockS, this.blockScratch, 1);
        }

        const associatedDataLength = 8 * associatedData.byteLength;
        const ciphertextDataLength = 8 * ciphertext.byteLength;
        this.blockScratch.writeBigInt64BE(BigInt(associatedDataLength));
        this.blockScratch.writeBigInt64BE(BigInt(ciphertextDataLength), 8);

        this.ghash(this.blockS, this.blockScratch, 1);
        this.gctr(output, this.blockJ, 1, this.blockS);
    }
Example #12
Source File: contest.ts    From CodePal with GNU General Public License v3.0 6 votes vote down vote up
async init(){
        try{
            assert(this.type !== "FUTURE");
            // const rcpcValue = "6164ef00544d3b5266657b2349cea803";
            const { data } = await axios.get(this.contestLink);
                                    
            const $ = cheerio.load(data);

            // const contestName = $('.rtable > tbody:nth-child(1) > tr:nth-child(1) > th:nth-child(1) > a:nth-child(1)');
            // this.name = contestName.text();

            let problemIndices = $('table.problems > tbody > tr > td.id > a');
            let problemNames = $('tr > td > div > div > a');

            assert(problemIndices.length === problemNames.length);
            for(let i = 0; i < problemNames.length; i++){
                let index = $(problemIndices[i]).text().trim();
                let name = $(problemNames[i]).text().trim();

                let p = new ProblemClass(this.contestID, index, name);
                this.problems.push(p);
            }
        }
        catch{
            console.log('Could not find contest. Either the codeforces servers are down or internet connection is not stable');
        }
    }
Example #13
Source File: mockedDatastore.ts    From AIPerf with MIT License 6 votes vote down vote up
private async getFinalMetricData(trialJobId: string): Promise<any> {
        const metrics: MetricDataRecord[] = await this.getMetricData(trialJobId, "FINAL");
        assert(metrics.length <= 1);
        if (metrics.length == 1) {
            return metrics[0];
        } else {
            return undefined;
        }
    }
Example #14
Source File: s3.ts    From backend with MIT License 5 votes vote down vote up
/// Returns a URL for a given key (it is not ensured whether the file for that key exists or is even publicly accessible)
export function accessURLForKey(key: string) {
    assert(ACCESS_DOMAIN_NAME, `Cannot create access URL for key ${key} because the ACCESS_DOMAIN_NAME is undefined. Please consider setting the appropriate environment variables to make the file bucket work.`);
    return new URL(key, `https://${ACCESS_DOMAIN_NAME}`).href;
}
Example #15
Source File: io.service.ts    From emutypekov with GNU General Public License v3.0 5 votes vote down vote up
static readFileSync(input: Path): string {
    assert(fs.lstatSync(input).isFile());
    return fs.readFileSync(input, 'utf-8');
  }
Example #16
Source File: io.service.ts    From emutypekov with GNU General Public License v3.0 5 votes vote down vote up
static readDirSync(input: Path): string[] {
    assert(fs.lstatSync(input).isDirectory());
    return fs.readdirSync(input);
  }
Example #17
Source File: index.ts    From backend with MIT License 5 votes vote down vote up
/**
 * @api {GET} /certificate/:certificateId?lang=... getCertificateConfirmation
 * @apiVersion 1.1.0
 * @apiDescription
 * View a certificate
 *
 * Returns the certificate as PDF
 *
 * @apiParam (URL Parameter) {string} certificateId UUID of the certificate
 * @apiParam (URL Query)     {string} lang=de The language
 *
 * @apiName getCertificate
 * @apiGroup Certificate
 *
 * @apiExample {curl} Curl
 * curl -k -i -X GET https://api.corona-school.de/api/certificate/000000001-0000-0000-0701-1b4c4c526384
 *
 * @apiUse StatusNoContent
 * @apiUse StatusBadRequest
 * @apiUse StatusUnauthorized
 * @apiUse StatusForbidden
 * @apiUse StatusInternalServerError
 */
export async function getCertificateEndpoint(req: Request, res: Response) {
    try {
        const { certificateId } = req.params;
        let { lang } = req.query;
        const requestor = res.locals.user as Student;
        assert(requestor, "No user set");

        if (lang === undefined) {
            lang = DefaultLanguage;
        }

        if (!LANGUAGES.includes(lang as Language)) {
            return res.status(400).send("Language not known");
        }

        if (typeof certificateId !== "string") {
            return res.status(400).send("Missing parameter certificateId");
        }

        const pdf = await getCertificatePDF(certificateId, requestor, lang as Language);

        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Length': pdf.length
        });
        return res.end(pdf);
    } catch (error) {
        if (error instanceof CertificateError) {
            return res.status(400).send(error.message);
        }

        logger.error("Failed to generate certificate confirmation", error);
        return res.status(500).send("<h1>Ein Fehler ist aufgetreten... ?</h1>");
    }
}
Example #18
Source File: index.ts    From backend with MIT License 5 votes vote down vote up
/* When introducing new notifications, it might sometimes make sense to schedule them "in retrospective" once for all existing users,
   as if the user took that action at actionDate */
export async function actionTakenAt(actionDate: Date, user: Person, actionId: string, notificationContext: NotificationContext, apply: boolean) {
    assert(user.active, "Cannot trigger action taken at for inactive users");

    const notifications = await getNotifications();
    const relevantNotifications = notifications.get(actionId);

    if (!relevantNotifications) {
        throw new Error(`Notification.actionTakenAt found no notifications for action '${actionId}'`);
    }

    const reminders = relevantNotifications.toSend.filter(it => it.delay);
    const remindersToCreate: Omit<ConcreteNotification, "id" | "error">[] = [];

    const userId = getUserIdTypeORM(user);

    for (const reminder of reminders) {
        if (reminder.delay * HOURS_TO_MS + +actionDate < Date.now() && !reminder.interval) {
            // Reminder was sent in the past and will not be sent in the future
            logger.debug(`Reminder(${reminder.id}) won't be scheduled in the future of ${actionDate.toISOString()}`);
            continue;
        }

        let sendAt = reminder.delay * HOURS_TO_MS + +actionDate;
        if (sendAt < Date.now()) {
            assert(reminder.interval > 0);
            const intervalCount = Math.ceil((Date.now() - sendAt) / (reminder.interval * HOURS_TO_MS));
            sendAt += intervalCount * reminder.interval * HOURS_TO_MS;
            assert(Date.now() > sendAt);
        }

        logger.debug(`Reminder(${reminder.id}) for action at ${actionDate.toISOString()} will be send at ${new Date(sendAt).toISOString()}`);

        remindersToCreate.push({
            notificationID: reminder.id,
            state: ConcreteNotificationState.DELAYED,
            sentAt: new Date(sendAt),
            userId,
            contextID: notificationContext.uniqueId,
            context: notificationContext
        });

    }

    if (apply && remindersToCreate.length > 0) {
        const remindersCreated = await prisma.concrete_notification.createMany({
            data: remindersToCreate
        });

        logger.info(`Notification.actionTakenAt scheduled ${remindersCreated.count} reminders for User(${userId}) at ${remindersToCreate.map(it => it.sentAt.toDateString())}`);
    }

    return remindersToCreate;
}
Example #19
Source File: mailjet.ts    From backend with MIT License 5 votes vote down vote up
mailjetChannel: Channel = {
    type: 'mailjet',
    async send(notification: Notification, to: Person, context: Context, concreteID: number) {
        assert(notification.mailjetTemplateId !== undefined, "A Notification delivered via Mailjet must have a 'mailjetTemplateId'");

        const senderEmail = senderEmails[notification.sender ?? NotificationSender.SUPPORT];
        assert(senderEmail !== undefined, "Unknown sender emails");

        const message: any = { // unfortunately the Typescript types do not match the documentation https://dev.mailjet.com/email/reference/send-emails#v3_1_post_send
            From: {
                Email: senderEmail
            },
            To: [
                {
                    Email: to.email
                }
            ],
            TemplateID: notification.mailjetTemplateId,
            TemplateLanguage: true,
            Variables: context,
            Attachments: context.attachments,
            CustomID: `${concreteID}`,
            TemplateErrorReporting: {
                Email: "[email protected]"
            }
        };

        if (context.replyToAddress) {
            message.ReplyTo = {
                Email: context.replyToAddress
            };
        }

        let sandboxMode = false;

        if (process.env.MAILJET_LIVE === "TEST") {
            message.Subject = `TESTEMAIL`;
            logger.warn(`Mail is in Test Mode`);
        } else if (process.env.MAILJET_LIVE != "1") {
            logger.warn(`Mail is in Sandbox Mode`);
            sandboxMode = true;
        }

        if (!mailjetSmtp.auth.user || !mailjetSmtp.auth.pass) {
            throw new Error(`Missing credentials for Mailjet API! Are MAILJET_USER and MAILJET_PASSWORD passed as env variables?`);
        }

        const mailjet = mailjetAPI.connect(mailjetSmtp.auth.user, mailjetSmtp.auth.pass);

        let requestOptions: mailjetAPI.Email.SendParams = {
            SandboxMode: sandboxMode,
            Messages: [
                message
            ]
        };

        logger.debug(`Sending Mail(${message.TemplateID}) to ${context.user.email} with options:`, requestOptions);

        const { body } = await mailjet.post("send", { version: "v3.1" }).request(requestOptions);

        if (!body.Messages || body.Messages.length !== 1) {
            throw new Error(`Mailjet API responded with invalid body`);
        }

        const result = body.Messages[0];

        if (result.Status !== "success") {
            const errorMessages = (result as any).Errors.map(error => error.ErrorMessage).join(", ");

            throw new Error(`Mailjet Message Delivery failed: ${errorMessages}`);
        }

        logger.info(`Sent Mail(${message.TemplateID})`);
    },

    canSend: (notification: Notification) => {
        return notification.mailjetTemplateId !== undefined;
    }
}
Example #20
Source File: Hello.model.ts    From cyan with MIT License 5 votes vote down vote up
private async testSort2(trx: TransactionScope) {
    const fozRepo = trx.getRepository(FozEntity);
    const fozId = await fozRepo.save({ id: (() => "UUID_SHORT()") as any, name: "foz_1", createdAt: new Date() });

    const bazRepo = trx.getRepository(BazEntity);
    const bazId1 = await bazRepo.save({ id: (() => "UUID_SHORT()") as any, fozId: BigInt(fozId) });
    const bazId2 = await bazRepo.save({ id: (() => "UUID_SHORT()") as any, fozId: BigInt(fozId) });

    const barRepo = trx.getRepository(BarEntity);
    const barId1 = await barRepo.save({
      id: (() => "UUID_SHORT()") as any,
      bazId: BigInt(bazId1),
      baz2Id: BigInt(bazId1),
    });

    const barId2 = await barRepo.save({
      id: (() => "UUID_SHORT()") as any,
      bazId: BigInt(bazId2),
      baz2Id: BigInt(bazId2),
    });

    const fooRepo = trx.getRepository(FooEntity);
    const fooId1 = await fooRepo.save({
      id: (() => "UUID_SHORT()") as any,
      barId: BigInt(barId1),
    });

    const fooId2 = await fooRepo.save({
      id: (() => "UUID_SHORT()") as any,
      barId: BigInt(barId2),
    });

    const fooSort = await fooRepo.findOne({
      order: [as => `${as[".bar.baz"]}.FOZ_ID DESC`, { id: "ASC" }],
      where: { id: [BigInt(fooId1), BigInt(fooId2)] },
    });

    assert(BigInt(fooSort.bar.baz.foz.id) === BigInt(fozId), "BigInt(fooSort.bar.baz.foz.id) === BigInt(fozId)");

    const keysExpected = ["id", "name", "worldId", "world", "createdAt"];
    const keys = getEntityProperties(HelloEntity);
    const column = getColumnByEntityProperty(HelloEntity, "worldId");

    keys.sort();
    keysExpected.sort();

    assert(keys.join("|") === keysExpected.join("|") && column === "WORLD_ID");
  }
Example #21
Source File: Hello.model.ts    From cyan with MIT License 5 votes vote down vote up
private async testSort1(trx: TransactionScope) {
    const fozRepo = trx.getRepository(FozEntity);
    const fozId1 = await fozRepo.save({ id: (() => "UUID_SHORT()") as any, name: "foz_1", createdAt: new Date() });
    const fozId2 = await fozRepo.save({ id: (() => "UUID_SHORT()") as any, name: "foz_2", createdAt: new Date() });

    const bazRepo = trx.getRepository(BazEntity);
    const bazId1 = await bazRepo.save({ id: (() => "UUID_SHORT()") as any, fozId: BigInt(fozId1) });
    const bazId2 = await bazRepo.save({ id: (() => "UUID_SHORT()") as any, fozId: BigInt(fozId2) });

    const barRepo = trx.getRepository(BarEntity);
    const barId1 = await barRepo.save({
      id: (() => "UUID_SHORT()") as any,
      bazId: BigInt(bazId1),
      baz2Id: BigInt(bazId1),
    });

    const barId2 = await barRepo.save({
      id: (() => "UUID_SHORT()") as any,
      bazId: BigInt(bazId2),
      baz2Id: BigInt(bazId2),
    });

    const fooRepo = trx.getRepository(FooEntity);
    const fooId1 = await fooRepo.save({
      id: (() => "UUID_SHORT()") as any,
      barId: BigInt(barId1),
    });

    const fooId2 = await fooRepo.save({
      id: (() => "UUID_SHORT()") as any,
      barId: BigInt(barId2),
    });

    const fooSort1 = await fooRepo.findOne({ order: { id: "DESC" }, where: { id: [BigInt(fooId1), BigInt(fooId2)] } });

    assert(BigInt(fooSort1.id) === BigInt(fooId2), "BigInt(fooSort1.id) === BigInt(fooId2)");

    const fooSort2 = await fooRepo.findOne({
      order: as => `${as[".bar.baz.foz"]}.ID DESC`,
      where: { id: [BigInt(fooId1), BigInt(fooId2)] },
    });

    assert(BigInt(fooSort2.bar.baz.foz.id) === BigInt(fozId2), "BigInt(fooSort2.bar.baz.foz.id) === BigInt(fozId2)");
  }
Example #22
Source File: joinExit.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
async function joinAndExitPool(
  getPoolId: () => Promise<string>,
  numTokens: number,
  transferTokens: boolean,
  joinData: unknown,
  exitData: unknown,
  stageIdx = 1
) {
  const poolId: string = await getPoolId();
  const { address: poolAddress } = await vault.getPool(poolId);
  const pool: Contract = await deployedAt('v2-pool-weighted/WeightedPool', poolAddress);
  const joinRequest = {
    assets: pickTokenAddresses(tokens, numTokens),
    maxAmountsIn: Array(numTokens).fill(MAX_UINT256),
    userData: joinData,
    fromInternalBalance: !transferTokens,
  };
  const exitRequest = {
    assets: pickTokenAddresses(tokens, numTokens),
    minAmountsOut: Array(numTokens).fill(0),
    userData: exitData,
    fromInternalBalance: !transferTokens,
  };

  let receipt;
  let bpt;

  for (let idx = 1; idx <= stageIdx; idx++) {
    receipt = await (
      await vault.instance.connect(trader).joinPool(poolId, trader.address, trader.address, joinRequest)
    ).wait();
    console.log(`${printGas(receipt.gasUsed)} gas for join ${idx}`);

    bpt = await pool.balanceOf(trader.address);

    // check token balances
    assert(bpt.toString() == BPTAmount.mul(idx).toString(), 'Did not actually join pool');
  }

  // Now exit the pool
  for (let idx = 1; idx <= stageIdx; idx++) {
    receipt = await (
      await vault.instance.connect(trader).exitPool(poolId, trader.address, trader.address, exitRequest)
    ).wait();
    console.log(`${printGas(receipt.gasUsed)} gas for exit ${idx}`);

    bpt = await pool.balanceOf(trader.address);
    assert(bpt.toString() == BPTAmount.mul(stageIdx - idx).toString(), 'Did not actually exit pool');
  }

  bpt = await pool.balanceOf(trader.address);
  assert(bpt.toString() == '0', 'Did not actually exit pool');
}
Example #23
Source File: index.ts    From backend with MIT License 4 votes vote down vote up
/**
 * @api {POST} /certificate/create getCertificate
 * @apiVersion 1.1.0
 * @apiDescription
 * Create a certificate
 *
 * It is only available for students.
 *
 * @apiParam (JSON Body) {string} pupil UUID of the pupil
 * @apiParam (JSON body) {number} endDate Unix Timestamp for the end date
 * @apiParam (JSON body) {string} subjects Must be a comma seperated string of the subjects. Only subjects that are matched are available
 * @apiParam (JSON body) {number} hoursPerWeek Hours per week helped
 * @apiParam (JSON body) {number} hoursTotal Total hours helped
 * @apiParam (JSON body) {string} medium Support medium
 * @apiParam (JSON body) {string} categories String of category texts for pupil's student description, separated by newlines
 * @apiParam (JSON body) {string} automatic if set, the pupil will automatically receive a signature request
 *
 * @apiName getCertificate
 * @apiGroup Certificate
 *
 * @apiExample {curl} Curl
 * curl -k -i -X GET https://api.corona-school.de/api/certificate/00000000-0000-0002-0001-1b4c4c526364/00000000-0000-0001-0001-1b4c4c526364
 *
 * @apiUse Authentication
 *
 * @apiUse StatusNoContent
 * @apiUse StatusBadRequest
 * @apiUse StatusUnauthorized
 * @apiUse StatusForbidden
 * @apiUse StatusInternalServerError
 */
export async function createCertificateEndpoint(req: Request, res: Response) {
    try {
        assert(res.locals.user, "Must be logged in");

        const { pupil, automatic, endDate, subjects, hoursPerWeek, hoursTotal, medium, activities, ongoingLessons } = req.body;
        const requestor = res.locals.user as Student;

        if (requestor instanceof Pupil) {
            return res.status(403).send("Only students may request certificates");
        }

        if (!pupil || !endDate || !subjects || hoursPerWeek === undefined || hoursTotal === undefined || !medium || !activities) {
            return res.status(400).send("Missing parameters");
        }

        if (automatic !== undefined && typeof automatic !== "boolean") {
            return res.status(400).send("automatic must be boolean");
        }

        if (typeof endDate !== "number") {
            return res.status(400).send("endDate must be a number");
        }

        if (!Array.isArray(subjects) || subjects.some(it => typeof it !== "string")) {
            return res.status(400).send("subjects must be an array of strings");
        }

        if (typeof hoursPerWeek !== "number" || hoursPerWeek < 0) {
            return res.status(400).send("hoursPerWeek must be a positive number");
        }

        if (typeof hoursTotal !== "number" || hoursTotal < 0) {
            return res.status(400).send("hoursTotal must be a positive number");
        }

        if (!CERTIFICATE_MEDIUMS.includes(medium)) {
            return res.status(400).send(`medium must be one of ${CERTIFICATE_MEDIUMS}`);
        }

        if (!Array.isArray(activities) || activities.some(it => typeof it !== "string")) {
            return res.status(400).send("categories must be an array of strings");
        }

        if (ongoingLessons !== undefined && typeof ongoingLessons !== "boolean") {
            return res.status(400).send("ongoingLessons must be boolean");
        }

        let state = automatic ? CertificateState.awaitingApproval : CertificateState.manual;

        let params: ICertificateCreationParams = {
            endDate,
            subjects: subjects.join(","),
            hoursPerWeek,
            hoursTotal,
            medium,
            activities: activities.join("\n"),
            ongoingLessons,
            state
        };

        // Students may only request for their matches

        const certificate = await createCertificate(requestor, pupil, params);

        return res.json({ uuid: certificate.uuid, automatic });
    } catch (error) {
        if (error instanceof CertificateError) {
            return res.status(400).send(error.message);
        }

        logger.error("Unexpected format of express request: " + error.message);
        logger.debug(req, error);
        return res.status(500).send("Internal server error");
    }
}
Example #24
Source File: Hello.model.ts    From cyan with MIT License 4 votes vote down vote up
private async testRawCol(trx: TransactionScope) {
    await trx.execute(`
      CREATE TABLE IF NOT EXISTS TEST_RAW_COL (
          ID BIGINT(20) NOT NULL AUTO_INCREMENT,
          NUM_1 BIGINT(20) DEFAULT NULL,
          NUM_2 BIGINT(20) DEFAULT NULL,
          CREATED_AT DATETIME DEFAULT NULL,
          PRIMARY KEY (ID)
      )
    `);

    const repo = trx.getRepository(TestRawColEntity);

    const numA1 = Math.floor(Math.random() * 100000 + 10000);
    const numA2 = Math.floor(Math.random() * 100000 + 10000);

    const insertedA = await repo.save({
      num1: numA1,
      num2: numA2,
    });

    const numB1 = Math.floor(Math.random() * 1000);
    const numB2 = Math.floor(Math.random() * 1000);

    const insertedB = await repo.save({
      num1: numB1,
      num2: numB2,
    });

    const foundSE = await repo.findOne({ where: { id: BigInt(insertedB) }, select: ["id", "numSum"] });

    assert(Object.keys(foundSE).length === 2 && BigInt(foundSE.numSum) === BigInt(numB1 + numB2));

    const foundA = await repo.findOne({ where: { id: BigInt(insertedA) } });

    assert(BigInt(foundA.numSum) === BigInt(numA1) + BigInt(numA2), "BigInt(foundA.numSum) === BigInt(numA1) + BigInt(numA2)");

    const foundS = await repo.findOne({ where: { numSum: numA1 + numA2 } });

    assert(BigInt(foundS.numSum) === BigInt(numA1) + BigInt(numA2), "foundS.numSum === BigInt(numA1) + BigInt(numA2)");

    const foundSMA = await repo.find({ where: { numSum: [numA1 + numA2, numB1 + numB2] }, order: { numSum: "ASC" } });

    assert(foundSMA.length >= 2, "foundSMA.length >= 2");
    assert(
      foundSMA.findIndex(x => BigInt(x.numSum) === BigInt(numA1 + numA2)) >
        foundSMA.findIndex(x => BigInt(x.numSum) === BigInt(numB1 + numB2)),
      `foundSMA.findIndex(${foundSMA.findIndex(x => BigInt(x.numSum) === BigInt(numA1 + numA2))} > ${foundSMA.findIndex(
        x => BigInt(x.numSum) === BigInt(numB1 + numB2)
      )})`
    );

    const foundSMD = await repo.find({ where: { numSum: [numA1 + numA2, numB1 + numB2] }, order: { numSum: "DESC" } });

    assert(foundSMD.length >= 2, "foundSMD.length >= 2");
    assert(
      foundSMD.findIndex(x => BigInt(x.numSum) === BigInt(numA1 + numA2)) <
        foundSMD.findIndex(x => BigInt(x.numSum) === BigInt(numB1 + numB2)),
      `foundSMD.findIndex(${foundSMD.findIndex(x => BigInt(x.numSum) === BigInt(numA1 + numA2))} < ${foundSMD.findIndex(
        x => BigInt(x.numSum) === BigInt(numB1 + numB2)
      )})`
    );

    const foundEA = await repo.find({ where: { numSum: [] } });

    assert(foundEA.length === 0, "foundEA.length === 0");

    const foundGTE = await repo.find({ where: { numSum: { ">=": numA1 + numA2 } } });

    assert(
      foundGTE.length && !foundGTE.find(x => BigInt(x.numSum) < BigInt(numA1 + numA2)),
      "foundGTE.length && !foundGTE.find(x => BigInt(x.numSum) < BigInt(numA1 + numA2))"
    );

    const foundLTE = await repo.find({ where: { numSum: { "<=": numA1 + numA2 } } });

    assert(
      foundLTE.length && !foundLTE.find(x => BigInt(x.numSum) > BigInt(numA1 + numA2)),
      "foundLTE.length && !foundLTE.find(x => BigInt(x.numSum) > BigInt(numA1 + numA2))"
    );
  }
Example #25
Source File: Hello.model.ts    From cyan with MIT License 4 votes vote down vote up
async test(): Promise<void> {
    await this.transactionWith<HelloEntity>(async scope => {
      await scope.execute(`
        CREATE TABLE IF NOT EXISTS HELLO (
            ID BIGINT(20) NOT NULL AUTO_INCREMENT,
            WORLD_ID BIGINT(20) DEFAULT NULL,
            NAME VARCHAR(128) DEFAULT NULL,
            CREATED_AT DATETIME DEFAULT NULL,
            PRIMARY KEY (ID)
        )
      `);

      await scope.execute(`
        CREATE TABLE IF NOT EXISTS WORLD (
            ID BIGINT(20) NOT NULL AUTO_INCREMENT,
            UNIVERSE_ID BIGINT(20) DEFAULT NULL,
            NAME VARCHAR(128) DEFAULT NULL,
            CREATED_AT DATETIME DEFAULT NULL,
            PRIMARY KEY (ID)
        )
      `);

      await scope.execute(`
        CREATE TABLE IF NOT EXISTS UNIVERSE (
            ID BIGINT(20) NOT NULL AUTO_INCREMENT,
            NAME VARCHAR(128) DEFAULT NULL,
            CREATED_AT DATETIME DEFAULT NULL,
            PRIMARY KEY (ID)
        )
      `);

      await scope.execute(`
        CREATE TABLE IF NOT EXISTS FOO (
            ID BIGINT(20) NOT NULL AUTO_INCREMENT,
            BAR_ID BIGINT(20) DEFAULT NULL,
            CREATED_AT DATETIME DEFAULT NULL,
            PRIMARY KEY (ID)
        )
      `);

      await scope.execute(`
        CREATE TABLE IF NOT EXISTS BAR (
            ID BIGINT(20) NOT NULL AUTO_INCREMENT,
            BAZ_ID BIGINT(20) DEFAULT NULL,
            BAZ2_ID BIGINT(20) DEFAULT NULL,
            CREATED_AT DATETIME DEFAULT NULL,
            PRIMARY KEY (ID)
        )
      `);

      await scope.execute(`
        CREATE TABLE IF NOT EXISTS BAZ (
            ID BIGINT(20) NOT NULL AUTO_INCREMENT,
            FOZ_ID BIGINT(20) DEFAULT NULL,
            CREATED_AT DATETIME DEFAULT NULL,
            PRIMARY KEY (ID)
        )
      `);

      await scope.execute(`
        CREATE TABLE IF NOT EXISTS FOZ (
            ID BIGINT(20) NOT NULL AUTO_INCREMENT,
            NAME VARCHAR(128) DEFAULT NULL,
            CREATED_AT DATETIME DEFAULT NULL,
            PRIMARY KEY (ID)
        )
      `);

      await scope.execute(`
        CREATE TABLE IF NOT EXISTS MUL_PRI (
            PRIMARY_ID BIGINT(20) NOT NULL,
            SECONDARY_ID BIGINT(20) NOT NULL,
            FOO VARCHAR(128) DEFAULT NULL,
            BAR VARCHAR(128) DEFAULT NULL,
            PRIMARY KEY (PRIMARY_ID, SECONDARY_ID)
        )
      `);

      await scope.execute(`
        CREATE TABLE IF NOT EXISTS MUL_PRI_JOIN (
            ID BIGINT(20) NOT NULL AUTO_INCREMENT,
            FOO VARCHAR(128) DEFAULT NULL,
            PRIMARY_ID BIGINT(20) DEFAULT NULL,
            SECONDARY_ID BIGINT(20) DEFAULT NULL,
            PRIMARY KEY (ID)
        )
      `);

      const worldRepo = scope.getRepository(WorldEntity);
      const worldId = await worldRepo.save({
        id: (() => "UUID_SHORT()") as any,
        name: "world",
        createdAt: null,
      });

      const repo = scope.getRepository(HelloEntity);

      const save1Name = `${Math.random()}-${new Date().getTime()}-${Math.random()}`;
      const save1 = await repo.save({
        id: (() => "UUID_SHORT()") as any,
        worldId: BigInt(worldId),
        name: save1Name,
        createdAt: null,
      });

      assert(save1 > 100000000, "save1 > 100000000");

      const found1 = await repo.findOne({ where: { id: save1 as bigint } });

      assert(found1.id === BigInt(save1), "found1.id");
      assert(found1.worldId === BigInt(worldId), "found1.worldId");
      assert(found1.name === save1Name, "found1.name");
      assert(found1.createdAt === null, "found1.createdAt");
      assert(found1.world && typeof found1.world === "object", "found1.world");
      assert(found1.world.id === BigInt(worldId), "found1.world.id");
      assert(found1.world.name === "world", "found1.world.name");
      assert(found1.world.createdAt === null, "found1.world.createdAt");

      const foundSpSelect = await repo.findOne({ where: { id: save1 as bigint }, select: ["name"] });

      assert(Object.keys(foundSpSelect).join(",") === "name");

      const foundSpSelectJoin = await repo.findOne({ where: { id: save1 as bigint }, select: ["name", "world"] });

      assert(Object.keys(foundSpSelectJoin).join(",") === "name,world");

      const foundLike = await repo.findOne({ where: { name: { LIKE: save1Name } } });

      assert(foundLike.id === BigInt(save1), "foundLike.id");

      const foundLikeBegin = await repo.findOne({ where: { name: { "LIKE%": save1Name.slice(0, -1) } } });

      assert(foundLikeBegin.id === BigInt(save1), "foundLikeBegin.id");

      const foundLikeEnd = await repo.findOne({ where: { name: { "%LIKE": save1Name.slice(1) } } });

      assert(foundLikeEnd.id === BigInt(save1), "foundLikeEnd.id");

      const foundLikeBetween = await repo.findOne({ where: { name: { "%LIKE%": save1Name.slice(1, -1) } } });

      assert(foundLikeBetween.id === BigInt(save1), "foundLikeBetween.id");

      const save2Id = BigInt(new Date().getTime());
      const save2Name = `${new Date().getTime()}`;
      const save2 = await repo.save({
        id: save2Id,
        name: save2Name,
        createdAt: new Date(),
      });

      assert(save2Id === save2, "save2Id === save2");

      const save3Id = BigInt(new Date().getTime() + 1234);
      const save3 = await repo.save({ id: save3Id } as any); // eslint-disable-line @typescript-eslint/no-unsafe-argument
      const found3 = await repo.findOne({ where: { id: save3 as bigint } });

      assert(found3.name.length === "2ca4d1cc-010c-11eb-8052-51e99d56d62f".length, "found3.name.length");
      assert(found3.createdAt.getTime() > 1000000, "found3.createdAt.getTime");

      const found = await repo.findOne({
        select: ["name"],
        where: {
          id: (k: string) => `${k} = ${save2Id}`,
          name: [save2Name, "xxx"],
        },
      });

      const founds = await repo.find({ limit: 3 });

      assert(!!found, "!!found");
      assert(founds.length > 0, "founds.length");

      const updateName = "xxx";
      const updateCreatedAt = new Date("2020-01-01");
      const entity: HelloEntity = {
        id: save2Id,
        name: updateName,
        createdAt: updateCreatedAt,
      };

      const queryOrder1 = await repo.findOne({
        where: {
          createdAt: {
            ">=": new Date("2000-01-01 00:00:00"),
            "<=": () => "CURRENT_TIMESTAMP()",
          },
        },
        order: { createdAt: "ASC" },
      });

      const queryOrder2 = await repo.findOne({
        where: {
          createdAt: {
            ">=": new Date("2000-01-01 00:00:00"),
            "<=": () => "CURRENT_TIMESTAMP()",
          },
        },
        order: { createdAt: (k: string) => `${k} IS NOT NULL, ${k} DESC` },
      });

      assert(queryOrder1.id && queryOrder2.id && String(queryOrder1.id) !== String(queryOrder2.id), "failed order by");

      const queryOrder3 = await repo.findOne({
        where: {
          createdAt: {
            ">=": new Date("2000-01-01 00:00:00"),
            "<=": () => "CURRENT_TIMESTAMP()",
          },
        },
        order: [{ createdAt: (k: string) => `${k} IS NOT NULL, ${k} DESC` }, { createdAt: "ASC" }],
      });

      assert(queryOrder1.id && queryOrder3.id && String(queryOrder1.id) !== String(queryOrder3.id), "failed order by");

      const queryOrder4 = await repo.findOne({
        where: {
          createdAt: {
            ">=": new Date("2000-01-01 00:00:00"),
            "<=": () => "CURRENT_TIMESTAMP()",
          },
        },
        order: [{ createdAt: "ASC" }, { createdAt: (k: string) => `${k} IS NOT NULL, ${k} DESC` }],
      });

      assert(queryOrder4.id && queryOrder3.id && String(queryOrder4.id) !== String(queryOrder3.id), "failed order by");

      const queryPagination1 = await repo.pagination({ page: 1, rpp: 2, order: { id: "DESC" } });
      const queryPagination2 = await repo.pagination({ page: 1, rpp: 1, order: { id: "DESC" } });
      const queryPagination3 = await repo.pagination({ page: 2, rpp: 1, order: { id: "DESC" } });

      assert(
        queryPagination1.items[0].id === queryPagination2.items[0].id,
        "queryPagination1.items[0].id === queryPagination2.items[0].id"
      );
      assert(
        queryPagination1.items[1].id === queryPagination3.items[0].id,
        "queryPagination1.items[1].id === queryPagination3.items[0].id"
      );

      const queryRaw = await scope.execute("SELECT ID FROM HELLO WHERE ID = ?", [queryPagination1.items[0].id]);

      assert(queryPagination1.items[0].id === queryRaw[0].ID, "queryPagination1.items[0].id === queryRaw[0].ID");

      await this.transactionWith(async innerScope => {
        const repoX = innerScope.getRepository(HelloEntity);
        const foundX = await repoX.findOne({ where: { id: queryPagination1.items[0].id } });

        assert(foundX.id === queryPagination1.items[0].id, "foundX.id");
      }, scope);

      const queryNotEq = await repo.pagination({
        where: {
          $AND: [
            { $AND: { id: [queryPagination1.items[0].id, queryPagination1.items[1].id] } },
            { $AND: { id: { "!=": queryPagination1.items[0].id } } },
          ],
        },
      });

      assert(queryNotEq.count === BigInt(1), "queryNotEq");

      const query1 = await repo.findOne({
        where: {
          createdAt: {
            ">=": new Date("2000-01-01 00:00:00"),
            "<=": () => "CURRENT_TIMESTAMP()",
          },
        },
      });

      assert(!!query1, "!!query1");

      const query2 = await repo.findOne({ where: { createdAt: { IS_NULL: true } } });

      assert(!!query2, "!!query2");

      const query3 = await repo.findOne({ where: { createdAt: { IS_NULL: false } } });

      assert(!!query3, "!!query3");

      const query4 = await repo.findOne({ where: { createdAt: { IS_NOT_NULL: true } } });

      assert(!!query4, "!!query4");

      const query5 = await repo.findOne({ where: { createdAt: { IS_NOT_NULL: false } } });

      assert(!!query5, "!!query5");

      const updated1 = await repo.update(entity, { update: ["name"], where: { name: updateName } });

      assert(updated1 === 0, "updated1");

      const updated2 = await repo.update(entity, { update: ["name"] });

      assert(updated2 === 1, "updated2");

      const updated3 = await repo.update(entity, { update: ["name"], where: { name: updateName } });

      assert(updated3 === 1, "updated3 failed");

      const updated4 = await repo.update(entity, { update: ["name"], where: { name: updateName, createdAt: updateCreatedAt } });

      assert(updated4 === 0, "updated4 failed");

      const updated5 = await repo.update(entity);

      assert(updated5 === 1, "updated5 failed");

      const updated6 = await repo.update(entity, { where: { name: updateName, createdAt: updateCreatedAt } });

      assert(updated6 === 1, "updated6 failed");

      const found6 = await repo.findOne({ where: { id: save2Id } });

      assert(found6.id === entity.id && found6.name === updateName && found6.createdAt.getTime() === updateCreatedAt.getTime());

      const deleted1 = await repo.delete(entity, { where: { name: `${updateName}--` } });

      assert(deleted1 === 0, "deleted1 failed");

      const deleted2 = await repo.delete(entity, { where: { name: updateName } });

      assert(deleted2 === 1, "deleted2 failed");

      const found7 = await repo.findOne({ where: { id: save2Id } });

      assert(found7 === null, "found7 failed");

      // Relations

      const fooRepo = scope.getRepository(FooEntity);
      const barRepo = scope.getRepository(BarEntity);
      const bazRepo = scope.getRepository(BazEntity);
      const fozRepo = scope.getRepository(FozEntity);

      const fozEntity: FozEntity = {
        id: undefined,
        name: String(Math.random()),
        createdAt: undefined,
      };

      await fozRepo.save(fozEntity);

      const latestFoz = await fozRepo.findOne({ order: { id: "ASC" } });

      const bazEntity: BazEntity = {
        id: undefined,
        fozId: latestFoz.id,
      };

      await bazRepo.save(bazEntity);

      const latestBaz = await bazRepo.findOne({ order: { id: "ASC" } });

      const barEntity: BarEntity = {
        id: undefined,
        bazId: latestBaz.id,
        baz2Id: latestBaz.id,
      };

      await barRepo.save(barEntity);

      const latestBar = await barRepo.findOne({ order: { id: "ASC" } });

      const fooEntity: FooEntity = {
        id: undefined,
        barId: latestBar.id,
      };

      await fooRepo.save(fooEntity);

      const latestFoo = await fooRepo.findOne({ order: { id: "ASC" } });

      assert(typeof latestFoo.id === "bigint");
      assert(latestFoo.bar.id === latestBar.id, "latestFoo.bar.id");
      assert(latestFoo.bar.baz.id === latestBaz.id, "latestFoo.bar.baz.id");
      assert(latestFoo.bar.baz.foz.id === latestFoz.id, "latestFoo.bar.baz.foz.id");
      assert(typeof latestFoo.bar.baz.foz.id === "bigint", "typeof latestFoo.bar.baz.foz.id");

      const helloEntities = await repo.find({ limit: 2 });
      const orWhere1 = await repo.find({ where: { $OR: { id: helloEntities[0].id, name: helloEntities[1].name } } });
      const orWhere2 = await repo.find({ where: { name: { $OR: [{ LIKE: helloEntities[0].name }, { LIKE: helloEntities[1].name }] } } });
      const andWhere1 = await repo.find({ where: { $AND: { id: helloEntities[0].id, name: helloEntities[0].name } } });
      const andWhere2 = await repo.find({ where: { $AND: { id: helloEntities[0].id, name: helloEntities[1].name } } });
      const andWhere3 = await repo.find({ where: { name: { $AND: [{ LIKE: helloEntities[0].name }, { LIKE: helloEntities[1].name }] } } });

      assert(orWhere1.length === 2, "orWhere.length === 2");
      assert(orWhere2.length === 2, "orWhere2.length === 2");
      assert(andWhere1.length === 1, "andWhere1.length === 1");
      assert(andWhere2.length === 0, "andWhere2.length");
      assert(andWhere3.length === 0, "andWhere3.length === 0");

      const andWhere4 = await repo.find({
        where: {
          $OR: [
            { $AND: { id: helloEntities[0].id, name: helloEntities[0].name } },
            { $AND: { id: helloEntities[1].id, name: helloEntities[1].name } },
          ],
        },
      });

      assert(
        andWhere4.length === 2 && andWhere4[0].id === helloEntities[0].id && andWhere4[1].id === helloEntities[1].id,
        "andWhere4.length === 2"
      );

      const andWhere5 = await repo.find({
        where: {
          $AND: [
            { $AND: { id: helloEntities[0].id, name: helloEntities[0].name } },
            { $AND: { id: helloEntities[1].id, name: helloEntities[1].name } },
          ],
        },
      });

      assert(andWhere5.length === 0, "andWhere5.length === 0");

      const mulPriRepo = scope.getRepository(MulPriEntity);
      const mulPriJoinRepo = scope.getRepository(MulPriJoinEntity);

      const primaryId = BigInt(`${new Date().getTime()}${Math.ceil(Math.random() * 1000000)}`);
      const secondaryId = primaryId + BigInt(1);
      const mulPriFoo = `${new Date().getTime()}-${Math.random()}-${Math.random()}`;

      await mulPriRepo.save({
        primaryId: primaryId,
        secondaryId: secondaryId,
        foo: mulPriFoo,
        bar: `${new Date().getTime()}`,
      });

      await mulPriRepo.save({
        primaryId: primaryId + BigInt(2),
        secondaryId: secondaryId + BigInt(3),
        foo: mulPriFoo,
        bar: `${new Date().getTime()}`,
      });

      await mulPriRepo.save({
        primaryId: primaryId + BigInt(3),
        secondaryId: secondaryId + BigInt(4),
        foo: mulPriFoo,
        bar: `${new Date().getTime()}`,
      });

      const countMulPri = await mulPriRepo.count({});

      await mulPriRepo.delete({
        primaryId: primaryId + BigInt(2),
        secondaryId: secondaryId + BigInt(3),
        foo: mulPriFoo,
        bar: `${new Date().getTime()}`,
      });

      const countMulPriAfter = await mulPriRepo.count({});

      assert(countMulPriAfter + BigInt(1) === countMulPri, "await mulPriRepo.count({}) + BigInt(1) === countMulPri");

      await mulPriJoinRepo.save({
        id: primaryId,
        foo: mulPriFoo,
        primaryId,
        secondaryId,
      });

      const mulPriJoinEntity = await mulPriJoinRepo.findOne({ where: { id: primaryId } });

      assert(mulPriJoinEntity.foo === mulPriFoo, "mulPriJoinEntity.foo === mulPriFoo");
      assert(mulPriJoinEntity.mul?.primaryId === primaryId, "mulPriJoinEntity.mul.primaryId === primaryId");

      await this.testRawCol(scope);
      await this.testSort1(scope);
      await this.testSort2(scope);

      return null;
    });

    return null;
  }
Example #26
Source File: app-config.ts    From office-booker with MIT License 4 votes vote down vote up
parseConfigFromEnv = (env: typeof process.env): Config => {
  const {
    REGION,
    COGNITO_USER_POOL_ID,
    SYSTEM_ADMIN_EMAILS,
    EMAIL_REGEX,
    OFFICE_QUOTAS,
    DEFAULT_WEEKLY_QUOTA,
    ADVANCE_BOOKING_DAYS,
    DATA_RETENTION_DAYS,
    COGNITO_CLIENT_ID,
  } = env;

  const requiredEnv = {
    REGION,
    COGNITO_USER_POOL_ID,
    SYSTEM_ADMIN_EMAILS,
    EMAIL_REGEX,
    OFFICE_QUOTAS,
    DEFAULT_WEEKLY_QUOTA,
    ADVANCE_BOOKING_DAYS,
    DATA_RETENTION_DAYS,
    COGNITO_CLIENT_ID,
  };

  if (
    REGION === undefined ||
    COGNITO_USER_POOL_ID === undefined ||
    SYSTEM_ADMIN_EMAILS === undefined ||
    EMAIL_REGEX === undefined ||
    OFFICE_QUOTAS === undefined ||
    EMAIL_REGEX === undefined ||
    DEFAULT_WEEKLY_QUOTA === undefined ||
    ADVANCE_BOOKING_DAYS === undefined ||
    DATA_RETENTION_DAYS === undefined ||
    COGNITO_CLIENT_ID === undefined
  ) {
    const missingEnvVars = Object.entries(requiredEnv)
      .filter(([, val]) => val === undefined)
      .map(([envVar]) => envVar);

    throw new Error(`Missing required env parameters: ${missingEnvVars.join(', ')}`);
  }

  const systemAdminEmails = SYSTEM_ADMIN_EMAILS.split(';');
  if (!systemAdminEmails.every(isValidEmail)) {
    throw new Error('Invalid email addresses in SYSTEM_ADMIN_EMAILS');
  }

  const officeQuotaConfigs = parseOfficeQuotas(OFFICE_QUOTAS);
  const defaultWeeklyQuota = Number.parseInt(DEFAULT_WEEKLY_QUOTA);
  assert(defaultWeeklyQuota >= 0, `DEFAULT_WEEKLY_QUOTA must be >= 0`);
  const advanceBookingDays = Number.parseInt(ADVANCE_BOOKING_DAYS);
  assert(advanceBookingDays >= 0, `ADVANCE_BOOKING_DAYS must be >= 0`);
  const dataRetentionDays = Number.parseInt(DATA_RETENTION_DAYS);
  assert(dataRetentionDays >= 0, `DATA_RETENTION_DAYS must be >= 0`);

  return {
    dynamoDBTablePrefix: env.DYNAMODB_PREFIX,
    authConfig: {
      type: 'cognito',
      cognitoUserPoolId: COGNITO_USER_POOL_ID,
      cognitoClientId: COGNITO_CLIENT_ID,
      region: REGION,
    },
    env: env.ENV,
    selfTestKey: env.SELFTESTKEY,
    selfTestUser: env.SELFTESTUSER,
    officeQuotas: officeQuotaConfigs,
    systemAdminEmails: systemAdminEmails,
    validEmailMatch: EMAIL_REGEX ? new RegExp(EMAIL_REGEX) : undefined,
    caseSensitiveEmail: env.CASE_SENSITIVE_EMAIL?.toLowerCase() === 'true',
    defaultWeeklyQuota,
    advanceBookingDays,
    dataRetentionDays,
    showTestBanner: env.SHOW_TEST_BANNER === 'true',
    readonly: env.READONLY === 'true',
    reasonToBookRequired: env.REASON_TO_BOOK_REQ === 'true',
    fromAddress: env.FROM_ADDRESS,
    notificationToAddress: env.NOTIFICATION_TO_ADDRESS,
  };
}