当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript Boom.expectationFailed函数代码示例

本文整理汇总了TypeScript中Boom.expectationFailed函数的典型用法代码示例。如果您正苦于以下问题:TypeScript expectationFailed函数的具体用法?TypeScript expectationFailed怎么用?TypeScript expectationFailed使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了expectationFailed函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: createAccount

export async function createAccount(server: Server, request: Request, reply: IReply)
{
    let account: Account = {
        _rev: undefined,
        _id: uuid(),
        apiKey: uuid(),
        dateCreated: new Date().toISOString(),
        hasCreatedRules: false,
        hasCreatedStages: false,
        isCanceled: false,
        planId: request.payload.planId,
        reasonForCancellation: undefined,
        shopify: {
            accessToken: undefined,
            chargeId: undefined,
            permissions: [],
            shopDomain: undefined,
            shopId: undefined,
            shopName: undefined,
        },
        stripe: {
            customerId: undefined,
            subscriptionId: undefined
        }
    }

    try
    {
        const create = await Accounts.Database.put(account);

        if (!create.ok)
        {
            console.error("Failed to create new account.", create);

            return reply(expectationFailed("Failed to create new account."));
        }

        account._rev = create.rev;
    }
    catch (e)
    {
        return reply(expectationFailed());
    }

    return reply(account);
}
开发者ID:nozzlegear,项目名称:stages-api,代码行数:46,代码来源:accounts-routes.ts

示例2: updateAccount

export async function updateAccount(server: Server, request: Request, reply: IReply)
{
    const id = request.params["id"];
    const apiKey = request.auth.credentials.apiKey;
    const accountToUpdate: Account = request.payload;
    let dbAccount: Account;

    // Get the original account
    try
    {
        dbAccount = await Accounts.findByApiKey(apiKey);

        // Only update the account if the ApiKey and Id match.
        if (!dbAccount || dbAccount._id !== id || dbAccount.apiKey !== apiKey)
        {
            return reply(notFound("No account find with that id and API key combination."));
        }
    }
    catch (e)
    {
        console.error("Failed to retrieve account when updating.", e);

        return reply(boom(e));
    }

    // Transfer update props to the dbAccount
    for (let prop in accountToUpdate)
    {
        dbAccount[prop] = accountToUpdate[prop];
    }

    // Never update the account's ID or apiKey
    dbAccount._id = id;
    dbAccount.apiKey = apiKey;

    try
    {
        const update = await Accounts.Database.put(accountToUpdate);

        if (!update.ok)
        {
            console.error("Failed to update account.", update);

            return reply(expectationFailed("Failed to update account."));
        }
        
        dbAccount._rev = update.rev;
    }
    catch (e)
    {
        console.error("Failed to update account.", e);

        return reply(boom(e));
    }

    return reply(dbAccount);
}
开发者ID:nozzlegear,项目名称:stages-api,代码行数:57,代码来源:accounts-routes.ts

示例3: postSettings

export async function postSettings(server: Server, request: Request, reply: IReply)
{
    function view(error: string, success?: boolean)
    {
        const props: SettingsProps = {
            title: "Account Settings.",
            success: !!success,
        }

        return reply.view("account/settings.js", props);
    }

    const validation = joi.validate<{newPassword: string, oldPassword: string, confirmPassword: string}>(request.payload, JoiValidation.postSettings);

    if (validation.error)
    {
        return view(humanizeError(validation.error));
    }

    const payload = validation.value;

    if (payload.confirmPassword !== payload.newPassword)
    {
        return view("New Password does not match the confirmation.");
    }

    const user = await Users.get<User>(request.auth.credentials.userId);

    // Ensure the user's current password is correct
    if(! compareSync(payload.oldPassword, user.hashedPassword))
    {
        return view("Old Password does not match.");
    }
    
    // Change the user's password
    user.hashedPassword = hashSync(payload.newPassword, 10);

    const update = await Users.put(user);

    if (!update.ok)
    {
        console.error("Failed to update user's password.", update);

        return reply(boom.expectationFailed("Failed to update user's password.", update));
    }

    await setUserAuth(request, user);

    return view(undefined, true);
}
开发者ID:nozzlegear,项目名称:deliver-on,代码行数:50,代码来源:account-routes.ts

示例4: createUser

export async function createUser(server: Server, request: Request, reply: IReply)
{
    const payload = request.payload as {name: string, username: string, password: string, accountId: string};
    const account = await Accounts.Database.get<Account>(payload.accountId.toLowerCase());

    if (!account)
    {
        return reply(notAcceptable(`No account with id of ${payload.accountId} exists.`));
    }

    // Ensure adding another user won't go over the account's plan limit.
    const userCount = await Users.countByAccountId(payload.accountId.toLowerCase());
    const plan = findPlan(account.planId);
    
    if (userCount >= plan.totalUsers)
    {
        return reply(notAcceptable("Account's plan has reached its maximum number of users."));
    }

    let user: User = {
        _id: payload.username,
        _rev: undefined,
        accountId: payload.accountId.toLowerCase(),
        hashedPassword: hashSync(payload.password, 10),
        name: payload.name,
    }

    try
    {
        const update = await Users.Database.put(user);

        if (!update.ok)
        {
            return reply(expectationFailed("Failed to create user.", update));
        }

        user._rev = update.rev;
    }
    catch (e)
    {
        console.error("Error thrown when creating user", e);

        throw e;
    }

    // Do not reflect the user's hashedPassword.
    user.hashedPassword = undefined;

    return reply(user).code(201);
}
开发者ID:nozzlegear,项目名称:stages-api,代码行数:50,代码来源:users-routes.ts

示例5: connectShopify

export async function connectShopify(server: Server, request: Request, reply: IReply): Promise<IBoom | Response>
{
    const query: {code: string, shop: string, hmac: string} = request.query;
    const accessToken = await authorize(query.code, query.shop, ShopifyApiKey, ShopifySecretKey);
    
    // Grab the user's shop name and id and their database record
    const shopData = (await new Shops(query.shop, accessToken).get({fields: ["name,id"]}));
    let user = await Users.get(request.auth.credentials.userId) as User;
    
    // Store the user's shop data
    user.shopifyDomain = query.shop;
    user.shopifyAccessToken = accessToken;
    user.shopifyShopName = shopData.name;
    user.shopifyShopId = shopData.id;
    
    const response = await Users.put(user);
    
    if (!response.ok)
    {
        console.error(`Failed to update user ${user._id}'s Shopify access token`);
        
        return reply(expectationFailed("Could not save Shopify access token."));
    }
    
    // Update the user's auth token
    await setUserAuth(request, user);

    const redirect = reply.redirect("/");

    if (!server.app.isLive)
    {
        // Don't create any webhooks unless this app is running on a real domain. Webhooks cannot point to localhost.
        return redirect;
    }

    // Create the AppUninstalled webhook immediately after the user accepts installation
    const webhooks = new Webhooks(user.shopifyDomain, user.shopifyAccessToken);

    // Ensure the webhook doesn't already exist
    if ((await webhooks.list({topic: "app/uninstalled", fields: ["id"], limit: 1})).length === 0)
    {
        await webhooks.create({
            address: `https://${Domain}/${WebhookRoutes.GetAppUninstalled}?shopId=${user.shopifyShopId}`,
            topic: "app/uninstalled"
        })
    }
    
    return redirect;
}
开发者ID:nozzlegear,项目名称:deliver-on,代码行数:49,代码来源:connect-routes.ts

示例6: postResetPassword

export async function postResetPassword(server: Server, request: Request, reply: IReply): Promise<IBoom | Response>
{
    const payload: {password: string, token: string, confirmPassword: string} = request.payload;
    const validation = joi.validate(payload, JoiValidation.resetPassword);
    const props: ResetPasswordProps = {
        title: "Reset your password.",
        token: payload.token,
    }

    if (validation.error)
    {
        props.error = humanizeError(validation.error);

        return reply.view("auth/reset_password.js", props);
    }

    if (payload.confirmPassword !== payload.password)
    {
        props.error = "Passwords do not match.";

        return reply.view("auth/reset_password.js", props);
    }

    // Ensure the user's password token is still valid
    const user = await findUserByPasswordResetToken(payload.token);

    if (!user || user.passwordResetToken !== payload.token || new Date(user.passwordResetRequestedAt as string) < new Date(new Date().getTime() - (30 * 60 * 1000) /* 30 minutes */))
    {
        props.error = "Your password reset request has expired.";

        return reply.view("auth/reset_password.js", props);
    }

    // Reset user's password
    user.passwordResetToken = undefined;
    user.passwordResetRequestedAt = undefined;
    user.hashedPassword = hashSync(payload.password, 10);

    const update = await Users.put(user);

    if (!update.ok)
    {
        console.error("Failed to save user's new password during password reset request.", update);

        return reply(boom.expectationFailed("Failed to save user's new password during password reset request.")); 
    }

    return reply.redirect(Routes.GetLogin);
}
开发者ID:nozzlegear,项目名称:deliver-on,代码行数:49,代码来源:auth-routes.ts

示例7: handleAppUninstalled

export async function handleAppUninstalled(server: Server, request: Request, reply: IReply): Promise<IBoom | Response>
{
    const query: {shopId: string, shop: string} = request.query;
    const user = await findUserByShopId(parseInt(query.shopId));

    if (!user)
    {
        console.log(`Could not find owner of shop id ${query.shop} during app/uninstalled webhook.`);

        // No user found with that shopId. This webhook may be a duplicate. Return OK to prevent Shopify resending the webhook.
        return reply(null);
    }

    // Shopify access token has already been invalidated at this point. Remove the user's Shopify data.
    user.shopifyAccessToken = undefined;
    user.shopifyDomain = undefined;
    user.shopifyShopId = undefined;
    user.shopifyShopName = undefined;

    const update = await Users.put(user);

    if (!update.ok)
    {
        console.error(`Failed to delete user ${user._id}'s Shopify data during app/uninstalled webhook.`, update);

        return reply(expectationFailed("Failed to delete user's Shopify data during app/uninstalled webhook."));
    }

    // Delete the user's data from the auth cache to force their next request to query the database.
    try
    {
        await deleteCacheValue(Caches.userAuth, user._id);
    }
    catch (e)
    {
        console.error("Failed to delete user data from auth cache after handling app/uninstalled webhook.", e);
    }

    return reply(null);
}
开发者ID:nozzlegear,项目名称:deliver-on,代码行数:40,代码来源:webhook-routes.ts

示例8: updateAppConfig

export async function updateAppConfig(server: Server, request: Request, reply: IReply)
{
    const validation = joi.validate<DeliverSettings>(request.payload, Validation.UpdateAppConfig)

    if (validation.error)
    {
        return reply(Boom.badData(humanizeError(validation.error), validation.error));
    }

    const payload = validation.value;
    let user: User;

    try 
    {
        user = await Users.get<User>(request.auth.credentials.userId);
    }
    catch (e)
    {
        console.error("Failed to retrieve user from database.", e);

        return reply(Boom.wrap(e));
    }

    user.appConfig = payload;

    const update = await Users.put(user);

    if (!update.ok)
    {   
        console.error("Failed to update user's app config.", update);

        return reply(Boom.expectationFailed("Failed to update user's app config."));
    }

    // Bust the cache so users on the shop see this change immediately.
    await setCacheValue(Caches.shopTagConfig, user.shopifyShopId.toString(), user.appConfig);

    return reply.continue() as any;
}
开发者ID:nozzlegear,项目名称:deliver-on,代码行数:39,代码来源:api-v1-routes.ts

示例9: postForgotPassword

export async function postForgotPassword(server: Server, request: Request, reply: IReply): Promise<IBoom | Response>
{
    const props: ForgotPasswordProps = {
        title: "Forgot your password?",
    }
    const validation = joi.validate<{username: string}>(request.payload, JoiValidation.forgotPassword);
    const payload = validation.value;

    if (validation.error)
    {
        props.username = payload.username;
        props.error = humanizeError(validation.error);

        return reply.view("auth/forgot_password.js");
    }
    
    let user: PasswordResetUser;

    try
    {
        user = await Users.get<PasswordResetUser>(payload.username.toLowerCase());
    }
    catch (e)
    {
        const error: pouch.api.PouchError = e;
        
        if (error.status !== 404)
        {
            throw e;
        }

        // Do not inform the user that the username does not exist
        return reply.redirect(Routes.GetResetSent);
    }

    const token = guid.v4();

    //Save the token to the user
    user.passwordResetToken = token;
    user.passwordResetRequestedAt = new Date();

    const update = await Users.put(user);

    if (!update.ok)
    {
        console.error("Failed to save password reset data to user model.", update);

        return reply(boom.expectationFailed("Failed to save password reset data."));
    }

    const url = `${getRequestDomain(request)}/${Routes.GetResetPassword}?token=${token}`.replace(/\/+/ig, "/");
    const message = {
        content: {
            from: {
                name: "Support",
                email: `support@${config.EmailDomain.replace(/^.*@/ig, "")}`,
            },
            subject: `[${config.AppName}] Reset your password.`,
            html: `<p>Hello,</p><p>You recently requested to reset your password for ${config.AppName}. Please click the link below to reset your password.</p><p><a href='${url}'>Click here to reset your password.</a></p><p>If you did not request a password reset, please ignore this email or reply to let us know. This password reset is only valid for the next 30 minutes.</p><p>Thanks, <br/> The ${config.AppName} Team</p>`
        },
        recipients: [{
            address: {
                email: payload.username,
            }
        }]
    }

    //Send the password reset email
    const transporter = createTransport({ transport: 'sparkpost', sparkPostApiKey: config.SparkpostKey } as any);

    transporter.sendMail(message, (error, info) =>
    {
        if (error)
        {
            return reply(boom.wrap(error));
        }

        return reply.redirect(Routes.GetResetSent);
    });
}
开发者ID:nozzlegear,项目名称:deliver-on,代码行数:80,代码来源:auth-routes.ts

示例10: postRegister

export async function postRegister(server: Server, request: Request, reply: IReply): Promise<any>
{
    let payload = request.payload as {
        username: string;
        password: string;  
    };
    let props: LoginProps = {
        username: payload.username,
        title: "Create an account" 
    };
    let validation = joi.validate(payload, JoiValidation.register);
    
    if (validation.error)
    {
        props.error = humanizeError(validation.error);
        
        return reply.view("auth/register.js", props); 
    }
    
    payload = validation.value;
    
    let user: User;
    
    //Check if a user with that name already exists
    try
    {
        user = await Users.get<User>(payload.username.toLowerCase());
        props.error = "A user with that username already exists.";
        
        return reply.view("auth/register.js", props);
    }
    catch (e)
    {
        let error: pouch.api.PouchError = e;
        
        if (error.status !== 404)
        {
            throw e;
        }
    }
    
    user = {
        _rev: undefined,
        _id: payload.username.toLowerCase(),
        username: payload.username,
        hashedPassword: hashSync(payload.password, 10),
        appConfig: {
            label: { 
                text: "Pick your delivery date:",
                textAlignment: "left",
                placement: "top",
            },
            input: {
                placeholder: "Click/tap to select",
            },
            placement: "right",
            format: "mm/dd/yyyy",
            addPickerToCheckout: false,
            allowChangeFromCheckout: false,
            maxDays: 7,
        }
    }
    
    const create = await Users.put(user);
    
    if (!create.ok)
    {
        return reply(boom.expectationFailed("Could not create new user."));
    }
    
    //Log the user in
    await setUserAuth(request, user);
    
    return reply.redirect("/setup");
}
开发者ID:nozzlegear,项目名称:deliver-on,代码行数:75,代码来源:auth-routes.ts


注:本文中的Boom.expectationFailed函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。