How to add and remove validated fields in yup validationSchema depending on layout condition - yup

Got react project and get list of needed inputs from BE. Creating validating Schema object need to use or not fields depending on condition exist this field in object from BE or not.
Got this solution but don't know is it ok?
const validationSchema = yup.object().shape({
...('phone' in fieldsList) && {'phone': yup.string().required('required')},
...('password' in fieldsList) && {'password': yup.string().required('required')},
...('email' in fieldsList) && {'email': yup.string().required('required')},
...('name' in fieldsList) && {'name': yup.string().required('required')},});

I think this would work
const validationSchema = yup.object();
if ('phone' in fieldsList) {
validationSchema.concat(yup.object({ 'phone': yup.string().required('required') }));
}
if ('password' in fieldsList) {
validationSchema.concat(yup.object({ 'password': yup.string().required('required') }));
}
if ('email' in fieldsList) {
validationSchema.concat(yup.object({ 'email': yup.string().required('required') }));
}
if ('email' in fieldsList) {
validationSchema.concat(yup.object({ 'email': yup.string().required('required') }));
}
If the validations are actually all the same, then you could:
fieldsList.forEach((name) => {
validationSchema.concat(yup.object({ [name]: yup.string().required('required') }));
})

Related

pass multiple params from flutter to node

I need to pass multiple query params from flutter to node. Do you know the best way? I need to pass the city, date, location.
Here is my dart file
Future<Appointment> searchSingleAppointment({
required BuildContext context,
required String city,
required String date,
required String location,
}) async {
Appointment appointment = Appointment(id: '', city: '', date: '', location: '', appointmentStatus: '', queue: 0);
try {
http.Response res =
await http.get(Uri.parse('$uri/appointments/search/'),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
// 'x-auth-token': userProvider.user.token,
});
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
appointment = Appointment.fromJson(res.body);
},
);
} catch (e) {
showSnackBar(context, e.toString());
}
return appointment;
}
}
and here's my node js file. I need those params so I can use them in my find()
appointmentRouter.get("/appointments/search/", async (req, res) => {
console.log(req.params);
try {
const appointment = await Appointment.find();
res.json(appointment);
} catch (e) {
res.status(500).json({ error: e.message });
}
});
Use queryParameters. Here is the example:
final queryParameters = {'search': 'blue', 'limit': '10'};
final uri = Uri.parse('https://example.com/page/').replace(queryParameters: queryParameters);
print(uri); // https://example.com/page/?search=blue&limit=10

option to manually flush/write body to browser when done

I have so far been unable to sort out this issue. I have a code that uses the MongoDb driver and whenever a do a fetch operation, i can no longer write to .response.body, e.g:
Once I call - await users.findOne({ email: req.email }) , I get an error when I do ctx.response.body.
As a workaround, is there a way i can force write the response, or a flag i can use to force oak not to close the response until i explicitly tell it to?
The error I get: The response is not writable.
Here is a sample snipped of my code:
private async create(context: Context, next: Function){
try {
interface UserSchema { email: string; password: string;}
const body = context.request.body()
assertEquals(body.type, 'json', 'app sent data in wrong format')
const req = await body.value
assertExists(req.email, 'email not provided')
assertExists(req.password, 'password not provided')
assertMatch(req.email, /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/, 'this does not look like a valid email address')
assertMatch(req.password, /(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/, 'password must contain: capital letter, small letter, number and must be 8 characters long')
const conn = context.state.db
const db = await conn.database('users')
const users = await db.collection<UserSchema>("users")
const user_id = await users.findOne({ email: req.email }) //bug *wont write to body
assert(!(user_id), 'email already exists')
const insertId = await users.insertOne({ email: req.email, password: req.password })
console.log('user added'); context.response.body = { 'error': false, 'msg': 'account created' }
} catch (e) { console.log({ 'error': e.name, 'msg': e.message })
//context.response.status = 500; context.response.body = { 'error': e.name, 'msg': e.message }
}
}

Apple Sign in Flutter Firestore overwrites displayname

I managed to get apple sign in working and create a userdoc on my firestore collection ('Users). However when I log out and sign in again with apple it overwrites the name "" ... Because it only logs the name the first time you log in with apple. How do I stop the name field to be overwritten everytime the same person signs out and in again?
case AuthorizationStatus.authorized:
try {
final res = await FirebaseAuth.instance.signInWithCredential(credential);
if (fixDisplayNameFromApple != null && res.user!.displayName == null) {
await res.user!.updateDisplayName(fixDisplayNameFromApple);
res.user!.reload();
}
FirebaseFirestore.instance.collection('Users').doc(res.user!.uid).set({
'name' : fixDisplayNameFromApple,
'email': res.user!.email,
'uid': res.user!.uid,
'image': 'https://merakiapp.be/wp-content/uploads/2022/06/appleUser.png',
}, SetOptions(merge: true));
return res.user;
} catch (e) {
print("error");
}
break;
I tried to check if the doc already exists so it doesn't create (overwrites) the original doc. But then it doesn't create a doc on firestore:
case AuthorizationStatus.authorized:
try {
final res = await FirebaseAuth.instance.signInWithCredential(credential);
if (fixDisplayNameFromApple != null && res.user!.displayName == null) {
await res.user!.updateDisplayName(fixDisplayNameFromApple);
res.user!.reload();
}
await FirebaseFirestore.instance
.collection("Users")
.doc(res.user!.uid)
.get()
.then((doc) {
if(doc.exists) {
return res.user;
} else {
FirebaseFirestore.instance.collection('Users').doc(res.user!.uid).set({
'name' : fixDisplayNameFromApple,
'email': res.user!.email,
'uid': res.user!.uid,
'image': 'https://merakiapp.be/wp-content/uploads/2022/06/appleUser.png',
}, SetOptions(merge: true));
return res.user;
}
});
} catch (e) {
print("error");
}
break;

How can I validate step by step using yup and react-hook-form?

const schema = yup.object().shape({
email: yup
.string()
.required()
.email('wrong email.')
.test('unique email', 'already using', async (value) => {
try {
const res = await axios.post('/accounts/emailcheck', { email: value });
return res.data.possible;
} catch (err) {
console.error(err);
}
}),
})
const { register, handleSubmit, formState: { errors } } = useForm({ mode: 'onBlur', resolver: yupResolver(schema) });
i want use axios only (requied, email) are ok.
But it works allways onBlur.
How can I validate step by step using yup and react-hook-form?

The property 'uid' can't be unconditionally accessed because the receiver can be 'null'

User is not working. I'm not uploading a collection in Firebase
try {
FirebaseAuth.instance.createUserWithEmailAndPassword
(email: kEmail.text, password: kPassword.text)
.then((value) {
userCollection.doc(value.user.uid).set({
'userName': kUserName,
'email': kEmail,
'password': kPassword,
'uid': value.user.uid
});
});
} catch (err) {
print(err.toString());
}
User can be null. So do null checking first like
try {
FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: kEmail.text, password: kPassword.text)
.then((value) {
if(value!=null && value.user != null){
userCollection.doc(value.user.uid).set({
'userName': kUserName,
'email': kEmail,
'password': kPassword,
'uid': value.user.uid
});
}else{
throw Error();
}
});
} catch (err) {
print(err.toString);
}
or a simple sol will be
..
Rest of the code...
userCollection.doc(value.user!.uid)
....Rest of the code //Add ! after user
change it to like this
(e.data() as dynamic)['myFieldOne']
https://i.stack.imgur.com/IhA7h.png