當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript hapi.IReply類代碼示例

本文整理匯總了TypeScript中hapi.IReply的典型用法代碼示例。如果您正苦於以下問題:TypeScript IReply類的具體用法?TypeScript IReply怎麽用?TypeScript IReply使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了IReply類的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: function

 handler: function(request: Request, reply: IReply) {
     reply.redirect('/blog' + request.path);
 }
開發者ID:csgpro,項目名稱:csgpro.com,代碼行數:3,代碼來源:index.ts

示例2: listAccounts

export async function listAccounts(server: Server, request: Request, reply: IReply)
{
    return reply(notImplemented());
}
開發者ID:nozzlegear,項目名稱:stages-api,代碼行數:4,代碼來源:accounts-routes.ts

示例3: handler

export default async function handler(req: Request, reply: IReply) {
  const { hackId: hackid } = req.params
  const requestDoc: HackChallengesRelationship.TopLevelDocument = req.payload

  const hack = await HackModel
    .findOne({ hackid }, 'hackid name challenges')
    .populate('challenges', 'challengeid')
    .exec()

  if (hack === null) {
    reply(Boom.notFound('Hack not found'))
    return
  }

  const challengeIdsToAdd = requestDoc.data.map((challenge) => challenge.id)
  const existingChallengeIds = challengeIdsToAdd.filter((challengeIdToAdd) => {
    return hack.challenges.some((actualchallenge) => actualchallenge.challengeid === challengeIdToAdd)
  })

  if (existingChallengeIds.length > 0) {
    reply(Boom.badRequest('One or more challenges are already challenges of this hack'))
    return
  }

  const challenges = await ChallengeModel
    .find({ challengeid: { $in: challengeIdsToAdd } }, 'challengeid name')
    .exec()

  if (challenges.length !== challengeIdsToAdd.length) {
    reply(Boom.badRequest('One or more of the specified challenges could not be found'))
    return
  }

  const challengeObjectIds = challenges.map((challenge) => challenge._id)

  const hacks = await HackModel
    .find({ challenges: { $in: challengeObjectIds } }, 'hackid')
    .exec()

  if (hacks.length > 0) {
    reply(Boom.badRequest('One or more of the specified challenges are already in a hack'))
    return
  }

  hack.challenges = hack.challenges.concat(challenges.map((challenge) => challenge._id))

  await hack.save()

  const eventBroadcaster: EventBroadcaster = req.server.app.eventBroadcaster
  challenges.forEach((challenge) => {
    eventBroadcaster.trigger('hacks_update_challenges_add', {
      hackid: hack.hackid,
      name: hack.name,
      entry: {
        challengeid: challenge.challengeid,
        name: challenge.name,
      },
    }, req.logger)
  })

  reply()
}
開發者ID:TechNottingham,項目名稱:Hack24-API,代碼行數:62,代碼來源:add-hack-challenges.ts

示例4: updateUser

export async function updateUser(server: Server, request: Request, reply: IReply)
{
    return reply(notImplemented());
}
開發者ID:nozzlegear,項目名稱:stages-api,代碼行數:4,代碼來源:users-routes.ts

示例5: handler

export default async function handler(req: Request, reply: IReply) {
  const query: any = {}

  req.logger.info('Filter: ', req.query)

  if (req.query['filter[name]']) {
    query.name = createEscapedRegex(req.query['filter[name]'])
  }

  const teams = await TeamModel
    .find(query, 'teamid name motto members entries')
    .sort({ teamid: 1 })
    .populate({
      path: 'members',
      select: 'userid name',
    })
    .populate({
      path: 'entries',
      select: 'hackid name challenges',
      populate: {
        path: 'challenges',
        select: 'challengeid name',
      },
    })
    .exec()

  const teamResponses = teams.map((team): TeamResource.ResourceObject => ({
    links: { self: `/teams/${encodeURIComponent(team.teamid)}` },
    type: 'teams',
    id: team.teamid,
    attributes: {
      name: team.name,
      motto: team.motto || null,
    },
    relationships: {
      members: {
        links: { self: `/teams/${encodeURIComponent(team.teamid)}/members` },
        data: team.members.map((member) => ({ type: 'users', id: member.userid })),
      },
      entries: {
        links: { self: `/teams/${encodeURIComponent(team.teamid)}/entries` },
        data: team.entries.map((hack) => ({ type: 'hacks', id: hack.hackid })),
      },
    },
  }))

  const includes: JSONApi.ResourceObject[] = [].concat(...teams.map((team): JSONApi.ResourceObject[] => {
    const members = team.members.map((member): UserResource.ResourceObject => ({
      links: { self: `/users/${member.userid}` },
      type: 'users',
      id: member.userid,
      attributes: { name: member.name },
    }))

    const entries = team.entries.map((hack): HackResource.ResourceObject => ({
      links: { self: `/hacks/${hack.hackid}` },
      type: 'hacks',
      id: hack.hackid,
      attributes: { name: hack.name },
      relationships: {
        challenges: {
          links: { self: `/hacks/${encodeURIComponent(hack.hackid)}/challenges` },
          data: hack.challenges.map((challenge) => ({ type: 'challenges', id: challenge.challengeid })),
        },
      },
    }))

    const challenges: ChallengeResource.ResourceObject[] = [].concat(...team.entries.map((hack) => (
      hack.challenges.map((challenge): ChallengeResource.ResourceObject => ({
        links: { self: `/challenges/${challenge.challengeid}` },
        type: 'challenges',
        id: challenge.challengeid,
        attributes: { name: challenge.name },
      }))
    )))

    return [...members, ...entries, ...challenges]
  }))

  const teamsResponse: TeamsResource.TopLevelDocument = {
    links: { self: `/teams` },
    data: teamResponses,
    included: includes,
  }

  reply(teamsResponse)
}
開發者ID:TechNottingham,項目名稱:Hack24-API,代碼行數:87,代碼來源:get-teams.ts

示例6: handler

export default async function handler(req: Request, reply: IReply) {
  const requestDoc: TeamResource.TopLevelDocument = req.payload

  const relationships = requestDoc.data.relationships
  let members: JSONApi.ResourceIdentifierObject[] = []
  let entries: JSONApi.ResourceIdentifierObject[] = []

  if (relationships) {
    if (relationships.members && relationships.members.data) {
      if (!Array.isArray(relationships.members.data)) {
        reply(Boom.badRequest())
        return
      }
      members = relationships.members.data
    }

    if (relationships.entries && relationships.entries.data) {
      if (!Array.isArray(relationships.entries.data)) {
        reply(Boom.badRequest())
        return
      }
      entries = relationships.entries.data
    }
  }

  const team = new TeamModel({
    teamid: slugify(requestDoc.data.attributes.name),
    name: requestDoc.data.attributes.name,
    motto: requestDoc.data.attributes.motto || null,
    members: [],
    entries: [],
  })

  let users: UserModel[] = []
  let hacks: HackModel[] = []

  if (members.length > 0) {
    users = await UserModel.find({
      userid: {
        $in: members.map((member) => member.id.toString()),
      },
    }, '_id userid name').exec()
    team.members = users.map((user) => user._id)
  }

  if (entries.length > 0) {
    hacks = await HackModel.find({
      hackid: {
        $in: entries.map((entry) => entry.id.toString()),
      },
    }, '_id hackid name').exec()
    team.entries = hacks.map((hack) => hack._id)
  }

  try {
    await team.save()
  } catch (err) {
    if (err.code === MongoDBErrors.E11000_DUPLICATE_KEY) {
      reply(Boom.conflict('Team already exists'))
      return
    }
    throw err
  }

  const teamResponse: TeamResource.TopLevelDocument = {
    links: {
      self: `/teams/${encodeURIComponent(team.teamid)}`,
    },
    data: {
      type: 'teams',
      id: team.teamid,
      attributes: {
        name: team.name,
        motto: team.motto,
      },
      relationships: {
        members: {
          links: { self: `/teams/${encodeURIComponent(team.teamid)}/members` },
          data: users.map((user) => ({ type: 'users', id: user.userid })),
        },
        entries: {
          links: { self: `/teams/${encodeURIComponent(team.teamid)}/entries` },
          data: hacks.map((hack) => ({ type: 'hacks', id: hack.hackid })),
        },
      },
    },
  }

  const eventBroadcaster: EventBroadcaster = req.server.app.eventBroadcaster
  eventBroadcaster.trigger('teams_add', {
    teamid: team.teamid,
    name: team.name,
    motto: team.motto,
    members: users.map((user) => ({ userid: user.userid, name: user.name })),
    entries: hacks.map((hack) => ({ hackid: hack.hackid, name: hack.name })),
  }, req.logger)

  reply(teamResponse).code(201)
}
開發者ID:TechNottingham,項目名稱:Hack24-API,代碼行數:99,代碼來源:create-team.ts

示例7: 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

示例8: 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

示例9: getLogout

export async function getLogout(server: Server, request: Request, reply: IReply)
{
    request.yar.clear(cookieName);
    
    return reply.redirect("/auth/login");
}
開發者ID:nozzlegear,項目名稱:deliver-on,代碼行數:6,代碼來源:auth-routes.ts


注:本文中的hapi.IReply類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。