Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: validated changeset #649

Merged
merged 9 commits into from
Apr 18, 2022
Merged

feat: validated changeset #649

merged 9 commits into from
Apr 18, 2022

Conversation

snewcomer
Copy link
Collaborator

@snewcomer snewcomer commented Apr 15, 2022

ref adopted-ember-addons/validated-changeset#168

Minor bump. Just adding a new changeset to the mix. See how people like it.

Limited API compared to the original Changeset.

ValidatedChangeset

  • ✂️ save
  • errors are required to be added to the Changeset in manually after validate
  • ✂️ cast
  • ✂️ merge
  • validate takes a callback with the sum of changes. In user land you will call changeset.validate((changes) => yupSchema.validate(changes))

See yup example

import Component from '@glimmer/component';
import { ValidatedChangeset } from 'ember-changeset';
import { action, get } from '@ember/object';
import { object, string } from 'yup';

class Foo {
  user = {
    name: 'someone',
    email: 'something@gmail.com',
  };
}

const FormSchema = object({
  cid: string().required(),
  user: object({
    name: string().required(),
    email: string().email(),
  })
});

export default class ValidatedForm extends Component {
  constructor() {
    super(...arguments);

    this.model = new Foo();
    this.changeset = ValidatedChangeset(this.model);
  }

  @action
  async setChangesetProperty(path, evt) {
    this.changeset.set(path, evt.target.value);
    try {
      await this.changeset.validate((changes) => FormSchema.validate(changes));
      this.changeset.removeError(path);
      await this.model.save();
    } catch (e) {
      this.changeset.addError(e.path, { value: this.changeset.get(e.path), validation: e.message });
    }
  }

  @action
  async submitForm(changeset, event) {
    event.preventDefault();

    changeset.execute();
  }
}

@snewcomer snewcomer self-assigned this Apr 15, 2022
@snewcomer snewcomer marked this pull request as ready for review April 18, 2022 02:40
@snewcomer snewcomer merged commit 538b68a into master Apr 18, 2022
@snewcomer snewcomer deleted the sn/yup-changeset branch April 18, 2022 02:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant