typescript - Jak rozšířit základní uživatelský schéma v better-auth
Snažím se rozšířit schéma uživatelského účtu v better-auth (používám NextJS a MongoDB). Snažil jsem se postupovat podle kroků v dokumentaci, ale nakonec mi TypeScript říká, že nová pole, která přidávám, nejsou rozpoznána.
Toto je můj soubor Auth.ts: (tohle není moc)
export const auth = betterAuth({
database: mongodbAdapter(client.db()), // adapt it into mongodb (our database)
emailAndPassword: {
enabled: true,
},
user: {
additionalFields: {
full_name: {
type: "string",
required: true,
defaultValue: "NO_NAME",
},
... among other fields
}
},
});
type Session = typeof auth.$Infer.Session
Toto je můj soubor auth_client, kde vyvozuji pole, která jsem přidal v auth
export const authClient = createAuthClient({
plugins: [inferAdditionalFields<typeof auth>()],
baseURL: clientEnvs.NEXT_PUBLIC_DOMAIN,
});
Tady se snažím provést registraci
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [full_name, setFullName] = useState('');
.. among others
...
const { data, error } = await authClient.signUp.email(
{
email,
password,
name,
full_name,
... among others
},
... the rest is how the program will react
Na konci dostanu tuto chybu (v editoru):
[{
"code": "2353",
"message": "Object literal may only specify known properties, and 'full_name' does not exist in type 'Prettify<InferSignUpEmailCtx<{ plugins: { id: \"additional-fields-client\"; $InferServerPlugin: { id: \"additional-fields\"; schema: { user: { fields: { full_name: { type: \"string\"; required: true; defaultValue: string; }; description: { ...; }; languages: { ...; }; role: { ...; }; phone_number: { ...; }; }; }; session:...'.",
}]
Co považuji za velmi zvláštní (pravděpodobně kvůli mé neznalosti TypeScriptu) je, že full_name JE zahrnuto v chybové zprávě (InferServerPlugin: { id: \"additional-fields\"; schema: { user: { fields(ZDE): { full_name: { )
Odpověď č. 1
V souboru auth.ts byste měli přidat pole, která chcete do konfiguračního objektu.
export const auth = betterAuth({
user: {
additionalFields: {
phone: {
type: 'string',
required: false,
defaultValue: null,
input: true // allow user to set role - false with hide this field,
}
}
}
})
Také musíte přidat pole do konfiguračního objektu auth-client. Zkoušel jsem to podle dokumentace, použitím pluginu „inferAddition...“ s typem auth, ale nefungovalo to, takže tento přístup mi pomohl a vyřešil problém.
export const { signIn, signOut, signUp, useSession } = createAuthClient({
baseURL: process.env.BETTER_AUTH_URL,
// plugins: [inferAdditionalFields<typeof auth>()]
plugins: [
inferAdditionalFields({
user: {
phone: {
type: 'string',
required: false
}
}
})
]
});
Nakonec přidejte pole do schématu Prisma, pokud ho používáte, a to by mělo problém vyřešit.
const { error } = await signUp.email({
name: data.name,
email: data.email,
password: data.password,
phone: '123' // autocomplete should work
});
