Login endpoint

This commit is contained in:
Luis Alvarez
2021-05-18 16:01:34 -05:00
parent eb2fd80ead
commit 1ba6049991
9 changed files with 128 additions and 3 deletions

View File

@@ -11,6 +11,7 @@ import fetchStoreApi from './utils/fetch-store-api'
import type { CartAPI } from './cart'
import type { CustomerAPI } from './customer'
import type { LoginAPI } from './login'
import login from './operations/login'
export interface BigcommerceConfig extends CommerceAPIConfig {
@@ -112,7 +113,7 @@ export const provider = {
export type Provider = typeof provider
export type APIs = CartAPI | CustomerAPI
export type APIs = CartAPI | CustomerAPI | LoginAPI
export type BigcommerceAPI<P extends Provider = Provider> = CommerceAPI<P>

View File

@@ -0,0 +1,10 @@
import type { GetAPISchema } from '@commerce/api'
import type { LoginSchema } from '../../types/login'
import type { BigcommerceAPI } from '..'
import login from './login'
export type LoginAPI = GetAPISchema<BigcommerceAPI, LoginSchema>
export type LoginEndpoint = LoginAPI['endpoint']
export const operations = { login }

View File

@@ -0,0 +1,49 @@
import { FetcherError } from '@commerce/utils/errors'
import type { LoginEndpoint } from '.'
const invalidCredentials = /invalid credentials/i
const login: LoginEndpoint['operations']['login'] = async ({
res,
body: { email, password },
config,
commerce,
}) => {
// TODO: Add proper validations with something like Ajv
if (!(email && password)) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
// TODO: validate the password and email
// Passwords must be at least 7 characters and contain both alphabetic
// and numeric characters.
try {
await commerce.login({ variables: { email, password }, config, res })
} catch (error) {
// Check if the email and password didn't match an existing account
if (
error instanceof FetcherError &&
invalidCredentials.test(error.message)
) {
return res.status(401).json({
data: null,
errors: [
{
message:
'Cannot find an account that matches the provided credentials',
code: 'invalid_credentials',
},
],
})
}
throw error
}
res.status(200).json({ data: null })
}
export default login

View File

@@ -0,0 +1 @@
export * from '@commerce/types/login'