Giter Club home page Giter Club logo

node-swiz's Introduction

node-swiz's People

Contributors

fourk avatar gdusbabek avatar grncdr avatar jirwin avatar jjbuchan avatar kami avatar mburns avatar phoebesimon avatar pquerna avatar robert-chiniquy avatar rphillips avatar russellhaering avatar simonvetter avatar wirehead avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-swiz's Issues

Swiz.prototype.deserialize handle JSON.parse errors?

In case of JSON.parse errors, the current Swiz.prototype.deserializee implementation will raise a SyntaxError (originating from the native JSON parser).

It would probably be better to propagate this error back to the callback passed to deserialize?

Swiz does not handle empty elements in XML

When dealing with empty elements in XML such as:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <ProfileResp>
        <CustomerBin>000001</CustomerBin>
        <CustomerMerchantID>xxxx</CustomerMerchantID>
        <CustomerName></CustomerName>
        <CustomerRefNum>37373646</CustomerRefNum>
        <CustomerProfileAction>READ</CustomerProfileAction>
        <ProfileProcStatus>0</ProfileProcStatus>
        <CustomerProfileMessage>Profile Request Processed</CustomerProfileMessage>
        <CustomerAddress1></CustomerAddress1>
        <CustomerAddress2></CustomerAddress2>
        <CustomerCity></CustomerCity>
        <CustomerState></CustomerState>
        <CustomerZIP></CustomerZIP>
        <CustomerEmail></CustomerEmail>
        <CustomerPhone></CustomerPhone>
        <CustomerProfileOrderOverrideInd>OI</CustomerProfileOrderOverrideInd>
        <OrderDefaultDescription></OrderDefaultDescription>
        <OrderDefaultAmount></OrderDefaultAmount>
        <CustomerAccountType>CC</CustomerAccountType>
        <Status>A</Status>
        <CCAccountNum>0000000000000000</CCAccountNum>
        <CCExpireDate></CCExpireDate>
        <ECPAccountDDA></ECPAccountDDA>
        <ECPAccountType></ECPAccountType>
        <ECPAccountRT></ECPAccountRT>
        <ECPBankPmtDlv></ECPBankPmtDlv>
        <SwitchSoloStartDate></SwitchSoloStartDate>
        <SwitchSoloIssueNum></SwitchSoloIssueNum>
        <RespTime></RespTime>
    </ProfileResp>
</Response>

Swiz creates the following object:

{ CustomerBin: '000001',
  CustomerMerchantID: 'xxxx',
  CustomerName: { CustomerName: null },
  CustomerRefNum: 37373646,
  CustomerAddress1: { CustomerAddress1: null },
  CustomerAddress2: { CustomerAddress2: null },
  CustomerCity: { CustomerCity: null },
  CustomerState: { CustomerState: null },
  CustomerZIP: { CustomerZIP: null },
  CustomerEmail: { CustomerEmail: null },
  CustomerPhone: { CustomerPhone: null },
  CustomerCountryCode: '',
  CustomerProfileAction: 'READ',
  CustomerProfileOrderOverrideInd: 'OI',
  CustomerProfileFromOrderInd: 'A',
  OrderDefaultDescription: { OrderDefaultDescription: null },
  OrderDefaultAmount: { OrderDefaultAmount: null },
  CustomerAccountType: 'CC',
  Status: 'A',
  CCAccountNum: 0000000000000000,
  CCExpireDate: { CCExpireDate: null },
  ECPAccountDDA: { ECPAccountDDA: null },
  ECPAccountType: { ECPAccountType: null },
  ECPAccountRT: { ECPAccountRT: null },
  ECPBankPmtDlv: { ECPBankPmtDlv: null },
  SwitchSoloStartDate: { SwitchSoloStartDate: null },
  SwitchSoloIssueNum: { SwitchSoloIssueNum: null },
  ProfileProcStatus: 0,
  CustomerProfileMessage: 'Profile Request Processed',
  RespTime: { RespTime: null } }

I would expect the javascript object for empty elements to be either

CustomerName: null

or

CustomerName: ''

All examples of empty elements in the documentation are self closing. The xml I am receiving from the service is not self closing but empty.

Here is the swiz definition object:

O('ProfileResp',
    {
      'fields': [
                F("CustomerBin", {'val':Chain().isString().inArray(["000001", "000002"])}),
            F("CustomerMerchantID", {'val':Chain().isString().notEmpty()}),
            F("CustomerName", {coerceTo:'string'}),
            F("CustomerRefNum", {coerceTo:'string'}),
            F("CustomerAddress1", {coerceTo:'string'}),
            F("CustomerAddress2", {coerceTo:'string'}),
            F("CustomerCity", {}),
            F("CustomerState", {}),
            F("CustomerZIP", {}),
            F("CustomerEmail", {}),
            F("CustomerPhone", {}),
            F("CustomerCountryCode", {}),
            F("CustomerProfileAction", {'val':Chain().isString().notEmpty().inArray(["C","R","U","D"])}),
            F("CustomerProfileOrderOverrideInd", {'val': Chain().isString().notEmpty().inArray(["NO","OI","OD","OA"])}),
            F("CustomerProfileFromOrderInd", {'val':Chain().isString().notEmpty().inArray(["A","S"])}),
            F("OrderDefaultDescription", {}),
            F("OrderDefaultAmount", {}),
            F("CustomerAccountType", {'val': Chain().isString().notEmpty().inArray(["CC","SW","EC","DP","ED","IM"])}),
            F("Status", {}),
            F("CCAccountNum", {}),
            F("CCExpireDate", {}),
            F("ECPAccountDDA", {}),
            F("ECPAccountType", {}),
            F("ECPAccountRT", {}),
            F("ECPBankPmtDlv", {}),
            F("SwitchSoloStartDate", {}),
            F("SwitchSoloIssueNum", {}),
            F("MBType", {}),
            F("MBOrderIdGenerationMethod", {}),
            F("MBRecurringStartDate", {}),
            F("MBRecurringEndDate", {}),
            F("MBRecurringNoEndDateFlag", {}),
            F("MBRecurringMaxBillings", {}),
            F("MBRecurringFrequency", {}),
            F("MBDeferredBillDate", {}),
            F("MBMicroPaymentMaxDollarValue", {}),
            F("MBMicroPaymentMaxBillingDays", {}),
            F("MBMicroPaymentMaxTransactions", {}),
            F("MBCancelDate", {}),
            F("MBRestoreBillingDate", {}),
            F("MBRemoveFlag", {}),
            F("EUDDCountryCode", {}),
            F("EUDDBankSortCode", {}),
            F("EUDDRibCode", {}),
            F("SDMerchantName", {}),
            F("SDProductDescription", {}),
            F("SDMerchantCity", {}),
            F("SDMerchantPhone", {}),
            F("SDMerchantURL", {}),
            F("SDMerchantEmail", {}),
            F("BillerReferenceNumber", {}),
            F("AccountUpdaterEligibility", {}),
            F("EUDDBankBranchCode", {}),
            F("EUDDIBAN", {}),
            F("EUDDBIC", {}),
            F("EUDDMandateSignatureDate", {}),
            F("EUDDMandateID", {}),
            F("EUDDMandateType", {}),           
        ],
      'plural': 'Profiles',
      'singular':'Profile'
  }),
    O('Response',{
    'fields':[
        F("ProfileResp" )
    ],
    'singular':'Response'
  })

valve chain.isDate(String)

It seems there is no valve chain.isData(String) yet.
This would be usefull to validate JavaScript "Date" objects that serialize to strings

valve chain.isDate(String)

It seems there is no valve chain.isData(String) yet.
This would be usefull to validate JavaScript "Date" objects that serialize to strings

Trying to get in touch regarding a security issue

Hey there!

I'd like to report a security issue but cannot find contact instructions on your repository.

If not a hassle, might you kindly add a SECURITY.md file with an email, or another contact method? GitHub recommends this best practice to ensure security issues are responsibly disclosed, and it would serve as a simple instruction for security researchers in the future.

Thank you for your consideration, and I look forward to hearing from you!

(cc @huntr-helper)

Having Trouble Wrapping my head around mapping complex xml

I have some xml formatted in hrxml which I want to convert to a JSON object.

Here is the xml:

<ns:Candidate xmlns:ns="http://ns.hr-xml.org/2007-04-15">
    <ns:CandidateRecordInfo>
        <ns:Id idOwner="Jobvite">
            <ns:IdValue name="applicationId">2123</ns:IdValue>
        </ns:Id>
        <ns:Status>New</ns:Status>
    </ns:CandidateRecordInfo>
    <ns:RelatedPositionPostings>
        <ns:PositionPosting>
            <ns:Id idOwner="Jobvite">
                <ns:IdValue name="requisitionId">20081023</ns:IdValue>
            </ns:Id>
            <ns:Title>Accountant</ns:Title>
        </ns:PositionPosting>
    </ns:RelatedPositionPostings>
    <ns:CandidateSupplier>
        <ns:SupplierId idOwner="Jobvite">
            <ns:IdValue name="sourcedBy">511</ns:IdValue>
        </ns:SupplierId>
        <ns:EntityName>Alex Recruiter</ns:EntityName>
        <ns:SourceType>
            <ns:NonStandardValue>Employee</ns:NonStandardValue>
        </ns:SourceType>
    </ns:CandidateSupplier>
    <ns:CandidateProfile>
        <ns:PersonalData>
            <ns:PersonId idOwner="Jobvite">
                <ns:IdValue name="candidateId">S234</ns:IdValue>
            </ns:PersonId>
            <ns:PersonName>
                <ns:GivenName>Jane</ns:GivenName>
                <ns:FamilyName>Doe</ns:FamilyName>
            </ns:PersonName>
            <ns:ContactMethod>
                <ns:Use>personal</ns:Use>
                <ns:Location>home</ns:Location>
                <ns:Telephone>
                    <ns:FormattedNumber>650-555-1212</ns:FormattedNumber>
                </ns:Telephone>
                <ns:Mobile>
                    <ns:FormattedNumber>650-555-1212</ns:FormattedNumber>
                </ns:Mobile>
                <ns:Fax>
                    <ns:FormattedNumber>415-555-1212</ns:FormattedNumber>
                </ns:Fax>
                <ns:InternetEmailAddress>[email protected]</ns:InternetEmailAddress>
                <ns:PostalAddress>
                    <ns:CountryCode>US</ns:CountryCode>
                    <ns:PostalCode>94118</ns:PostalCode>
                    <ns:Region>CA</ns:Region>
                    <ns:Municipality>San Francisco</ns:Municipality>
                    <ns:DeliveryAddress>
                        <ns:AddressLine>123 Main St.</ns:AddressLine>
                        <ns:AddressLine>2nd Floor</ns:AddressLine>
                    </ns:DeliveryAddress>
                </ns:PostalAddress>
            </ns:ContactMethod>
        </ns:PersonalData>
    </ns:CandidateProfile>
    <ns:Resume>
        <ns:NonXMLResume>
            <ns:TextResume>
                Jane Doe
                [email protected]
                408-555-1212
                I am a great candidate!
            </ns:TextResume>
        </ns:NonXMLResume>
    </ns:Resume>
    <ns:UserArea>
        <CustomFields xmlns="http://api.jobvite.com/action/api/v1">
            <Field type="Candidate" name="Candidate Field 3">Some value</Field>
        </CustomFields>
    </ns:UserArea>
</ns:Candidate>

I would like to have an object that results in:

{
    record_info:{
        applicationId: 'xxxx',
        status: 'new'
    },
    posting:{
        requisitionId: 'xxxxx',
        title: 'Some Title'
    },
    supplier:{
        sourcedBy: '511',
        name: 'Alex Recruiter',
        sorce_type: 'Employee'
    },
    profile:{
        candidateId: 'xxxx',
        name:{
            first: 'Jame',
            last: 'Doe'
        }
        contact_methods: {
            use: 'personal',
            location: 'home',
            phone: 'xxx-xxx-xxxx',
            mobile: 'xxx-xxx-xxxx',
            fax: 'xxx-xxx-xxxx',
            email: '[email protected]',
            postal_address: {
                country_code: 'US',
                postal_code: '94118',
                region: 'CA',
                municipality: 'San Fransisco',
                address_lines:[
                    '123 Main St.',
                    '2nd Floor'
                ]
            }
        }
    },
    resume: 'Jane Doe \
                [email protected] \
                408-555-1212 \
                I am a great candidate!'

}

My questions are:

  1. Is this even possible with swiz?
  2. How do I map an attribute name to a value as in the example?
  3. How many Object definitions do I need to make? Is it one for every nesting level in the xml?

how to deal with nested json data?

Hello,

I am trying to figure out how to deal with nested json data, but I couldn't figure out how to correctly do it (from looking at the blogpost and unit tests, etc).

I have a nested json structure:

{
  some: 'data',
  compound: {
    and: 'something else',
    foo: {
      bar:1
    }
  }
}

I am trying to write Obj/Field definitions that can be used to validate this structure (compound.foo.bar isInt, compound.and isString)

Am I supposed to manually validate.check the 'compound' and 'foo' part of the deserialised json or is there a way (using serializerType?) to hint the validator to use a certain definition of the defs structure for a certain part of the JSON data?

So far I am able to validate the 'toplevel' structure, but the problem is validating the nested data.

(it seems the validation will clean any items not in the defs structure, so I need it to 'know' about the nested items)

test-valve.js isn't doing async callbacks correctly

Take the following snippet, this is incorrect.

The test.finish needs to be called at the end.

  var v = new V({
    a: C().isAlpha()
  });

  // positive case
  var obj = { a: 'ABC' };
  var obj_ext = { a: 'ABC', b: 2 };
  v.check(obj_ext, function(err, cleaned) {
    assert.ifError(err);
    assert.deepEqual(cleaned, obj, 'alpha test');
  });

  // negative case
  var neg = { a: 'invalid/' };
  v.check(neg, function(err, cleaned) {
    assert.deepEqual(err.message, 'Invalid characters', 'alpha test (negative case)');
  });

  test.finish();

It needs to be refactored to do the test.finish at the end. Something like the snippet below

exports['test_validate_alpha'] = function(test, assert) {
  var v = new V({
        a: C().isAlpha()
      }),
      obj,
      obj_ext,
      neg;

  async.parallel([
    function (callback) {
      // positive case
      obj = { a: 'ABC' };
      obj_ext = { a: 'ABC', b: 2 };
      v.check(obj_ext, function(err, cleaned) {
        assert.ifError(err);
        assert.deepEqual(cleaned, obj, 'alpha test');
        callback();
      });
    },
    function(callback) {
      // negative case
      neg = { a: 'invalid/' };
      v.check(neg, function(err, cleaned) {
        assert.deepEqual(err.message, 'Invalid characters', 'alpha test (negative case)');
        callback();
      });
    }],
    function(err, results) {
      test.finish();
    }
  );
};

Collecting validation errors

Hi,

Does this library support collect validation errors for one checking step?
For example, I have a payload with 3 errors, but when I call a method Valve.check and it returns only 1 validation error then I fix it and got another error instead of all errors in one object.

Thank you.

Problems with deserialization

serialization.js (Swiz.prototype._emitFromDef )

1) Swiz.prototype._emitFromDef line 365

if (child._children.length === 1 && self._defFor(child._children[0].tag)) {
// if there is only one child and that child has its own def, assume that it is a complex object that has
// been serialized (as opposed to a simple hash)

I think that is not always right to have object insteadd of array even if there is only one child

...

I still may want to have items: [{item}] but not item: {item}

2) Swiz.prototype._emitFromDef line 375

if (grandChild.text.length > 0)

It checks if there is a text inside of tag but if there some line breaks in the file
-- if there is a line break .text will be not empty

text property wont be empty - I don't think that this is right (i used trim() for workaround).

3) Swiz.prototype._emitFromDef line 380

obj[child.tag].push(self._emitFromDef(grandChild, def));

It tries to deserialize grandChild with def of elem (passed to _emitFromDef)

Please write what do you think about it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.