budibase/packages/backend-core/src/users.ts

49 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-07-18 22:11:52 +02:00
import { ViewNames } from "./db/utils"
import { queryGlobalView } from "./db/views"
import { UNICODE_MAX } from "./db/constants"
import { User } from "@budibase/types"
2022-04-08 02:28:22 +02:00
/**
* Given an email address this will use a view to search through
* all the users to find one with this email address.
* @param {string} email the email to lookup the user by.
*/
2022-07-18 22:11:52 +02:00
export const getGlobalUserByEmail = async (email: String) => {
2022-04-08 02:28:22 +02:00
if (email == null) {
throw "Must supply an email address to view"
}
2022-07-18 22:11:52 +02:00
const response = await queryGlobalView<User>(ViewNames.USER_BY_EMAIL, {
2022-04-08 02:28:22 +02:00
key: email.toLowerCase(),
include_docs: true,
})
2022-04-12 13:34:36 +02:00
2022-07-18 22:11:52 +02:00
if (Array.isArray(response)) {
// shouldn't be able to happen, but need to handle just in case
throw new Error(`Multiple users found with email address: ${email}`)
}
2022-04-12 13:34:36 +02:00
return response
2022-04-08 02:28:22 +02:00
}
/**
* Performs a starts with search on the global email view.
*/
2022-07-18 22:11:52 +02:00
export const searchGlobalUsersByEmail = async (email: string, opts: any) => {
if (typeof email !== "string") {
throw new Error("Must provide a string to search by")
}
const lcEmail = email.toLowerCase()
// handle if passing up startkey for pagination
const startkey = opts && opts.startkey ? opts.startkey : lcEmail
2022-07-18 22:11:52 +02:00
let response = await queryGlobalView<User>(ViewNames.USER_BY_EMAIL, {
...opts,
startkey,
endkey: `${lcEmail}${UNICODE_MAX}`,
})
if (!response) {
response = []
}
return Array.isArray(response) ? response : [response]
}