التحقق من عدم تكرار القيم في قاعدة البيانات (البيانات الفريدة)

 بداية سنقوم بإضافة هذه الخدمات في الواجهة الخلفية حسب الحقول المطلوبة (Service):

 //------------------- For Add -----------------------
  async countUsersByNationalId(national_id: string) {
    return await this.UserRepository.count({
      where: {
        national_id: national_id
      }
    });
  }

  async countUsersByUsername(username: string) {
    return await this.UserRepository.count({
      where: {
        username: username
      }
    });
  }

  async countUsersByEmail(email: string) {
    return await this.UserRepository.count({
      where: {
        email: email.trim()
      }
    });
  }

  async countUsersByMobileNo(mobile_no: string) {
    return await this.UserRepository.count({
      where: {
        mobile_no: mobile_no
      }
    });
  }

  //------------------- For Edit -----------------------
  async countUsersByNationalIdForEdit(national_id: string, previous_national_id: string) {
    if (previous_national_id === national_id)
      return 0;

    return await this.UserRepository.count({
      where: {
        national_id: national_id
      }
    });
  }

  async countUsersByUsernameForEdit(username: string, old_username: string) {
    if (old_username === username)
      return 0;

    return await this.UserRepository.count({
      where: {
        username: username
      }
    });
  }

  async countUsersByEmailForEdit(email: string, old_email: string) {
    if (old_email === email)
      return 0;

    return await this.UserRepository.count({
      where: {
        email: email.trim()
      }
    });
  }

  async countUsersByMobileNoForEdit(mobile_no: string, old_mobile_no: string) {
    if (old_mobile_no === mobile_no)
      return 0;

    return await this.UserRepository.count({
      where: {
        mobile_no: mobile_no
      }
    });
  }


أما بالنسبة للـ Controller سيكون بهذا النحو:

  //------------------- For Add -----------------------
  @Get('count-users-by-national-id/:national_id')
  countUsersByNationalId(@Param('national_id') national_id: string) {
    if (national_id) {
      return this.usersService.countUsersByNationalId(national_id);
    } else {
      return 0;
    }
  }

  @Get('count-users-by-username/:username')
  countUsersByUsername(@Param('username') username: string) {
    if (username) {
      return this.usersService.countUsersByUsername(username);
    } else {
      return 0;
    }
  }

  @Get('count-users-by-email/:email')
  countUsersByEmail(@Param('email') email: string) {
    if (email) {
      return this.usersService.countUsersByEmail(email);
    } else {
      return 0;
    }
  }

  @Get('count-users-by-mobile-no/:mobile_no')
  countUsersByMobileNo(@Param('mobile_no') mobile_no: string) {
    if (mobile_no) {
      return this.usersService.countUsersByMobileNo(mobile_no);
    } else {
      return 0;
    }
  }

  //------------------- For Edit -----------------------
  @Get('count-users-by-national-id/:national_id/:previous_national_id')
  countUsersByNationalIdForEdit(@Param('national_id') national_id: string, @Param('previous_national_id') previous_national_id) {
    if (national_id) {
      return this.usersService.countUsersByNationalIdForEdit(national_id, previous_national_id);
    } else {
      return 0;
    }
  }

  @Get('count-users-by-username/:username/:old_username')
  countUsersByUsernameForEdit(@Param('username') username: string, @Param('old_username') old_username: string) {
    if (username) {
      return this.usersService.countUsersByUsernameForEdit(username, old_username);
    } else {
      return 0;
    }
  }

  @Get('count-users-by-email/:email/:old_email')
  countUsersByEmailForEdit(@Param('email') email: string, @Param('old_email') old_email: string) {
    if (email) {
      return this.usersService.countUsersByEmailForEdit(email, old_email);
    } else {
      return 0;
    }
  }

  @Get('count-users-by-mobile-no/:mobile_no/:old_mobile_no')
  countUsersByMobileNoForEdit(@Param('mobile_no') mobile_no: string, @Param('old_mobile_no') old_mobile_no: string) {
    if (mobile_no) {
      return this.usersService.countUsersByMobileNoForEdit(mobile_no, old_mobile_no);
    } else {
      return 0;
    }
  }

أما بالنسبة لخدمة الواجهة الأمامية ستكون بهذا النحو:

  countUsersByNationalId(national_id: string) {
    return this.http.get(`${this.api}/${this.table}/count-users-by-national-id/${national_id}`);
  }

  countUsersByUsername(username: string) {
    return this.http.get(`${this.api}/${this.table}/count-users-by-username/${username}`);
  }

  countUsersByMobileNo(mobile: string) {
    return this.http.get(`${this.api}/${this.table}/count-users-by-mobile-no/${mobile}`);
  }

  countUsersByEmail(email: string) {
    return this.http.get(`${this.api}/${this.table}/count-users-by-email/${email}`);
  }

طريقة الاستخدام للتحقق من وجود الحقول أو لا (في حالة الإضافة):

//Vareibales
  _existsNationalId: boolean = false;
  _existsEmail: boolean = false;
  _existsMobileNo: boolean = false;
  _existsUsername: boolean = false;

  existsEmail(event: string) {
    if (event) {
      this.usersService.countUsersByEmail(event).subscribe((res) => {
        setTimeout(() => {
          if (res.toString() === "1") {
            this._existsEmail = true;
          } else {
            this._existsEmail = false;
          }
        }, 500);
      },
        (error) => {
          this._existsEmail = false;
        });
    } else {
      this._existsEmail = false;
    }
  }

  existsNationalId(event: string) {
    if (event) {
      this.usersService.countUsersByNationalId(event).subscribe((res) => {
        setTimeout(() => {
          if (res.toString() === "1") {
            this._existsNationalId = true;
          } else {
            this._existsNationalId = false;
          }
        }, 500);
      },
        (error) => {
          this._existsNationalId = false;
        });
    } else {
      this._existsNationalId = false;
    }
  }

  existsUsername(event: string) {
    if (event) {
      this.usersService.countUsersByUsername(event).subscribe((res) => {
        setTimeout(() => {
          if (res.toString() === "1") {
            this._existsUsername = true;
          } else {
            this._existsUsername = false;
          }
        }, 500);
      },
        (error) => {
          this._existsUsername = false;
        });
    } else {
      this._existsUsername = false;
    }
  }

  existsMobileNo(event: string) {
    if (event) {
      this.usersService.countUsersByMobileNo(event).subscribe((res) => {
        setTimeout(() => {
          if (res.toString() === "1") {
            this._existsMobileNo = true;
          } else {
            this._existsMobileNo = false;
          }
        }, 500);
      },
        (error) => {
          this._existsMobileNo = false;
        });
    } else {
      this._existsMobileNo = false;
    }
  }
  //------------------ End ----------------------------

طريقة الاستخدام للتحقق من وجود الحقول أو لا (في حالة التعديل):

  oldUser: User = new User();
  ngOnInit() {
    this.usersService.getOneItem(this.id).subscribe(res => {
      this.oldUser = res;
    });
  }

  existsEmail(event: string) {
    if (event) {
      if (this.oldUser.email) {
        this.usersService.countUsersByEmailForEdit(event, this.oldUser.email).subscribe((res) => {
          setTimeout(() => {
            if (res.toString() === "1") {
              this._existsEmail = true;
            } else {
              this._existsEmail = false;
            }
          }, 500);
        },
          (error) => {
            this._existsEmail = false;
          });
      } else {
        this._existsEmail = false;
      }
    } else {
      this._existsEmail = false;
    }
  }

  existsNationalId(event: string) {
    if (event) {
      if (this.oldUser.national_id) {
        this.usersService.countUsersByNationalIdForEdit(event, this.oldUser.national_id).subscribe((res) => {
          setTimeout(() => {
            if (res.toString() === "1") {
              this._existsNationalId = true;
            } else {
              this._existsNationalId = false;
            }
          }, 500);
        },
          (error) => {
            this._existsNationalId = false;
          });
      } else {
        if (event) {
          this.usersService.countUsersByNationalId(event).subscribe((res) => {
            setTimeout(() => {
              if (res.toString() === "1") {
                this._existsNationalId = true;
              } else {
                this._existsNationalId = false;
              }
            }, 500);
          },
            (error) => {
              this._existsNationalId = false;
            });
        } else {
          this._existsNationalId = false;
        }
      }
    } else {
      this._existsNationalId = false;
    }
  }

  existsUsername(event: string) {
    if (event) {
      if (this.oldUser.username) {
        this.usersService.countUsersByUsernameForEdit(event, this.oldUser.username).subscribe((res) => {
          setTimeout(() => {
            if (res.toString() === "1") {
              this._existsUsername = true;
            } else {
              this._existsUsername = false;
            }
          }, 500);
        },
          (error) => {
            this._existsUsername = false;
          });
      } else {
        this._existsUsername = false;
      }
    } else {
      this._existsUsername = false;
    }
  }

  existsMobileNo(event: string) {
    if (event) {
      if (this.oldUser.mobile_no) {
        this.usersService.countUsersByMobileNoForEdit(event, this.oldUser.mobile_no).subscribe((res) => {
          setTimeout(() => {
            if (res.toString() === "1") {
              this._existsMobileNo = true;
            } else {
              this._existsMobileNo = false;
            }
          }, 500);
        },
          (error) => {
            this._existsMobileNo = false;
          });
      } else {
        this._existsMobileNo = false;
      }
    } else {
      this._existsMobileNo = false;
    }
  }

استدعاء الدوال عبر ملفات الـ HTML :

<!-- اسم المستخدم -->
<div class="col-sm-6">
  <mat-form-field class="w-100 mt-1" appearance="outline">
  <mat-label>{{'LABELS.USERNAME' |
    translate}}</mat-label>
    <input #username [(ngModel)]="user.username"
    (keyup)="existsUsername(user.username)"
    formControlName="username" maxlength="11" matInput
    type="text"
    [placeholder]="'PLACEHOLDERS.USERNAME' | translate"
    required>
    <mat-icon matSuffix class="icon-edit">person</mat-icon>
      <mat-error align="start"
    *ngIf="form.controls['username'].hasError('required')">
      {{'ERRORS.REQUIRED' | translate}}
    </mat-error>
  <mat-hint *ngIf="_existsUsername"
    style="color:red !important"
    class="animate__animated animate__fadeInRight">{{'ERRORS.EXISTS_VALUE'
  | translate}}</mat-hint>
    <mat-hint align="end">{{username.value.length}} /
    11</mat-hint>
  </mat-form-field>
</div>


شكراً على القراءة .....






























تعليقات

المشاركات الشائعة من هذه المدونة

ngx-extended-pdf-viewer

how to getting access token for https://fcm.googleapis.com/v1/projects/al-ayahya-co/messages:send for angular and backend nestjs

طريقة تفعيل زر Inline Keyboard في Telegram Bot