Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'apollo-server-core' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
// validate input
const schemas = yup.object().shape({
email: emailSchema.required(),
shortId: contestShortIdSchema.required(),
name: contestNameSchema.required(),
shortDescription: contestShortDescriptionSchema.required(),
description: contestDescriptionSchema.required(),
startTime: startTimeSchema.required(),
finishTime: finishTimeSchema.required(),
permittedLanguageIds: permittedLanguagesSchema.required(),
})
try {
args = await schemas.validate(args)
} catch (error) {
if (error instanceof yup.ValidationError) {
throw new ApolloError('Invalid Input', 'INVALID_INPUT', error.errors)
}
}
// check taken shortId
try {
await contestStore.getContestByShortId(args.shortId)
throw new ApolloError(
'Contest ID Already Taken',
'CONTEST_ID_ALREADY_TAKEN'
)
} catch (error) {
if (!(error instanceof NoSuchContest)) throw error
}
// check languages ids
const availableLangs = await languageStore.getAvailableLanguages()
const res = mockResponse(mockResponseOptions);
const graphQLOptions = await apolloServer.createGraphQLServerOptions(
req,
res
);
const { graphqlResponse } = await runHttpQuery([req, res], {
method: 'POST',
options: graphQLOptions,
query: {
// operation can be a string or an AST, but `runHttpQuery` only accepts a string
query: typeof operation === 'string' ? operation : print(operation),
variables
},
request: convertNodeHttpToRequest(req)
});
return JSON.parse(graphqlResponse) as T;
};
lastName: profile.name.familyName,
gender: profile.gender === '' && Gender.UNKNOWN,
avatar: profile.photos[0].value
})
)
}
return await tradeToken(user)
}
if (info) {
// console.log(info)
const { code } = info
switch (code) {
case 'ETIMEDOUT':
throw new ApolloError('Failed to reach Google: Try Again')
default:
throw new ApolloError('Something went wrong')
}
}
}
async forgotPassword(
@Args('email') email: string,
@Context('req') req: any
): Promise {
const user = await getMongoRepository(User).findOne({
where: {
'local.email': email,
isVerified: true,
},
})
if (!user) {
throw new ForbiddenError('User not found.')
}
const resetPassToken = await generateResetPassToken(user)
const existedEmail = await this.emailResolver.createEmail({
userId: user._id,
type: Type.FORGOT_PASSWORD,
})
// console.log(existedEmail)
await sendMail(
'forgotPassword',
user,
req,
resetPassToken,
async createSubscription(
@Args('source') source: string,
@Args('ccLast4') ccLast4: string,
@Context('currentUser') currentUser: User
): Promise {
// console.log(source)
if (currentUser.stripeId) {
throw new ForbiddenError('stripeId already existed.')
}
const email = currentUser.local
? currentUser.local.email
: currentUser.google
? currentUser.google.email
: currentUser.facebook.email
const customer = await stripe.customers.create({
email,
source,
plan: STRIPE_PLAN!,
})
// console.log(customer)
const user = await getMongoRepository(User).save(
async changeCreditCard(
@Args('source') source: string,
@Args('ccLast4') ccLast4: string,
@Context('currentUser') currentUser: User
): Promise {
// console.log(source)
if (!currentUser.stripeId || currentUser.type !== UserType.PREMIUM) {
throw new ForbiddenError('User not found.')
}
await stripe.customers.update(currentUser.stripeId, {
source,
})
const updateUser = await getMongoRepository(User).save(
new User({
...currentUser,
ccLast4,
})
)
return updateUser
}
async search(@Args('conditions') conditions: SearchInput): Promise {
let result
const { select, where, order, skip, take } = conditions
if (Object.keys(where).length > 1) {
throw new UserInputError('Your where must be 1 collection.')
}
const type = Object.keys(where)[0]
// const createdAt = { $gte: 0, $lte: new Date().getTime() }
result = await getMongoRepository(type).find({
where: where[type] && JSON.parse(JSON.stringify(where[type])),
order: order && JSON.parse(JSON.stringify(order)),
skip,
take,
})
// console.log(result)
if (result.length === 0) {
@Context('pubsub') pubsub: any,
@Context('req') req: any
): Promise {
try {
const { email, password } = input
let existedUser
existedUser = await getMongoRepository(User).findOne({
where: {
'local.email': email
}
})
if (existedUser) {
throw new ForbiddenError('User already exists.')
}
// Is there a Google account with the same email?
existedUser = await getMongoRepository(User).findOne({
where: {
$or: [{ 'google.email': email }, { 'facebook.email': email }]
}
})
if (existedUser) {
// Let's merge them?
const updateUser = await getMongoRepository(User).save(
new User({
...input,
local: {
@Context('pubsub') pubsub: any,
@Context('req') req: any
): Promise {
try {
const { email, password } = input
let existedUser
existedUser = await getMongoRepository(User).findOne({
where: {
'local.email': email,
},
})
if (existedUser) {
throw new ForbiddenError('User already exists.')
}
// Is there a Google account with the same email?
existedUser = await getMongoRepository(User).findOne({
where: {
$or: [{ 'google.email': email }, { 'facebook.email': email }],
},
})
if (existedUser) {
// Let's merge them?
const updateUser = await getMongoRepository(User).save(
new User({
...input,
local: {
requestVerify: async (_: any, { email }: { email: string }, ctx: any) => {
// Check if there is a user with that email
const user = await ctx.models.User.findOne({ email })
if (!user) {
throw new AuthenticationError(`No such user found for email: ${email}`)
}
if (user.verified) {
throw new AuthenticationError('This user has been verified already')
}
// Set a reset token and expiry on that user
const resetToken = await createRandomToken()
// Update user adding the reset token and expiry
const requestingUser = await ctx.models.User.updateOne(
{
_id: user._id
},
{
...user._doc,
verifyToken: resetToken.randomToken,
verifyTokenExpiry: resetToken.randomTokenExpiry
},
{ upsert: true }