Skip to content

Fix special characters encoding #116

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

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
- name: Use Node.js
uses: actions/setup-node@v1
with:
node-version: 12
node-version: 16
- name: Install
run: yarn install
- name: Run Lint
Expand Down
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
node_modules

_bundles
yarn.lock
yarn-error.log
build/
test-old/
Expand Down
42 changes: 24 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
This fork basically changes the way relationships are updated, to be compliant with json:api format. Original Spraypaint library has some added functionality, that might not be compatible with all backends.

---

# Spraypaint

JS Client for [Graphiti](https://graphiti-api.github.io/graphiti) similar to ActiveRecord.
Expand All @@ -9,44 +13,46 @@ Written in [Typescript](https://www.typescriptlang.org) but works in plain old E
Please see [our documentation page](https://graphiti-api.github.io/graphiti/js) for full usage. Below is a Typescript sample:

```ts
import { SpraypaintBase, Model, Attr, HasMany } from "spraypaint"
import { SpraypaintBase, Model, Attr, HasMany } from "spraypaint";

@Model()
class ApplicationRecord extends SpraypaintBase {
static baseUrl = "http://localhost:3000"
static apiNamespace = "/api/v1"
static baseUrl = "http://localhost:3000";
static apiNamespace = "/api/v1";
}

@Model()
class Person extends ApplicationRecord {
static jsonapiType = "people"
static jsonapiType = "people";

@Attr() firstName: string
@Attr() lastName: string
@Attr() firstName: string;
@Attr() lastName: string;

@HasMany() pets: Pet[]
@HasMany() pets: Pet[];

get fullName() {
return `${this.firstName} ${this.lastName}`
return `${this.firstName} ${this.lastName}`;
}
}

@Model()
class Pet extends ApplicationRecord {
static jsonapiType = "pets"
static jsonapiType = "pets";

@Attr() name: string
@Attr() name: string;
}

let { data } = await Person
.where({ name: 'Joe' })
.page(2).per(10)
.sort('name')
let { data } = await Person.where({ name: "Joe" })
.page(2)
.per(10)
.sort("name")
.includes("pets")
.all()
.all();

let names = data.map((p) => { return p.fullName })
console.log(names) // ['Joe Blow', 'Joe DiMaggio', ...]
let names = data.map((p) => {
return p.fullName;
});
console.log(names); // ['Joe Blow', 'Joe DiMaggio', ...]

console.log(data[0].pets[0].name) // "Fido"
console.log(data[0].pets[0].name); // "Fido"
```
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"@babel/plugin-transform-modules-commonjs": "7.2.0",
"@babel/preset-env": "7.3.1",
"@babel/register": "7.0.0",
"@types/chai": "^4.0.4",
"@types/chai": "4.2.14",
"@types/chai-as-promised": "^7.1.0",
"@types/chai-things": "^0.0.32",
"@types/fetch-mock": "5.12.2",
Expand All @@ -75,7 +75,7 @@
"@types/mocha": "^2.2.44",
"@types/node": "^8.0.58",
"@types/sinon": "^4.1.2",
"@types/sinon-chai": "^2.7.29",
"@types/sinon-chai": "3.2.5",
"@types/winston": "2.3.7",
"chai": "^4.1.2",
"chai-things": "^0.2.0",
Expand Down Expand Up @@ -106,5 +106,9 @@
"typescript-eslint-parser": "21.0.2",
"winston": "^2.3.1"
},
"resolutions": {
"@types/sinon": "9.0.8",
"@types/lodash": "4.14.165"
},
"version": "0.10.22"
}
5 changes: 5 additions & 0 deletions src/jsonapi-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export type JsonapiResponseDoc =
| JsonapiErrorDoc
export type JsonapiSuccessDoc = JsonapiCollectionDoc | JsonapiResourceDoc
export type JsonapiRequestDoc = JsonapiResourceRequest
export type JsonapiBulkRequestDoc = JsonapiResourceBulkRequest

export interface JsonapiDocMeta {
included?: JsonapiResource[]
Expand All @@ -24,6 +25,10 @@ export interface JsonapiResourceRequest extends JsonapiDocMeta {
data: JsonapiResource
}

export interface JsonapiResourceBulkRequest extends JsonapiDocMeta {
data: JsonapiResource[]
}

export interface JsonapiErrorDoc extends JsonapiDocMeta {
data: undefined
errors: JsonapiError[]
Expand Down
64 changes: 61 additions & 3 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ import { EventBus } from "./event-bus"
import {
JsonapiResource,
JsonapiResponseDoc,
JsonapiResourceIdentifier
JsonapiResourceIdentifier,
JsonapiResourceBulkRequest
} from "./jsonapi-spec"

import { cloneDeep } from "./util/clonedeep"
Expand Down Expand Up @@ -1027,6 +1028,63 @@ export class SpraypaintBase {
})
}

static async bulkSave<I extends SpraypaintBase>(
models: Array<I>
): Promise<boolean> {
if (!models || models.length === 0) {
return false
}

let firstModel = models[0]
let bulkJson: JsonapiResourceBulkRequest = { data: [] }

if (models.length === 1) {
return firstModel.save()
}

for (const m of models) {
if (m.klass.jsonapiType !== firstModel.klass.jsonapiType) {
throw new Error(
`Cannot bulk save different model types: received <${
firstModel.klass.jsonapiType
}> and <${m.klass.jsonapiType}>`
)
}

if (m.isPersisted) {
throw new Error(
`Cannot bulk save already persisted models: received model with id <${
m.id
}>`
)
}

const payload = new WritePayload(m)
bulkJson.data.push(payload.asJSON().data)
}

let url = firstModel.klass.url()
let verb: RequestVerbs = "post"
const request = new Request(
firstModel._middleware(),
firstModel.klass.logger
)
let response: any

try {
response = await request[verb](url, bulkJson, firstModel._fetchOptions())
} catch (err) {
throw err
}

return await firstModel._handleResponse(response, () => {
for (let i = 0; i < models.length; i++) {
const json = response.jsonPayload.data[i]
models[i].fromJsonapi(json, response.jsonPayload)
}
})
}

private async _handleAcceptedResponse(
response: any,
callback: DeferredActionCallback | undefined
Expand Down Expand Up @@ -1073,9 +1131,9 @@ export class SpraypaintBase {
// * remove the corresponding code from isPersisted and handle here (likely
// only an issue with test setup)
// * Make all calls go through resetRelationTracking();
resetRelationTracking(includeDirective: object) {
resetRelationTracking() {
this._originalRelationships = this.relationshipResourceIdentifiers(
Object.keys(includeDirective)
Object.keys(this.relationships)
)
}

Expand Down
8 changes: 6 additions & 2 deletions src/request.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import colorize from "./util/colorize"
import { MiddlewareStack } from "./middleware-stack"
import { ILogger, logger as defaultLogger } from "./logger"
import { JsonapiResponseDoc, JsonapiRequestDoc } from "./jsonapi-spec"
import {
JsonapiResponseDoc,
JsonapiRequestDoc,
JsonapiBulkRequestDoc
} from "./jsonapi-spec"

export type RequestVerbs = keyof Request

Expand Down Expand Up @@ -35,7 +39,7 @@ export class Request {

post(
url: string,
payload: JsonapiRequestDoc,
payload: JsonapiRequestDoc | JsonapiBulkRequestDoc,
options: RequestInit
): Promise<any> {
options.method = "POST"
Expand Down
7 changes: 7 additions & 0 deletions src/util/deserialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,13 @@ class Deserializer {
instance.isPersisted = true
instance.reset()

const instanceType: string = instance.klass.jsonapiType || ""
if (instanceType) {
if (!this.registry.get(instanceType)) {
this.registry.register(instanceType, instance.klass)
}
}

return instance
}

Expand Down
10 changes: 2 additions & 8 deletions src/util/parameterize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,9 @@ const parameterize = (obj: any, prefix?: string): string => {
return str.join("&")
}

// IE does not encode by default like other browsers
const maybeEncode = (value: string): string => {
var isBrowser =
typeof window !== "undefined" &&
typeof window.navigator.userAgent !== "undefined"
const isIE = isBrowser && window.navigator.userAgent.match(/(MSIE|Trident)/)
const isEncoded = typeof value === "string" && value.indexOf("%") !== -1
const shouldEncode = isBrowser && isIE && !isEncoded
return shouldEncode ? encodeURIComponent(value) : value
var isEncoded = typeof value === "string" && decodeURI(value) !== value
return isEncoded ? value : encodeURIComponent(value)
}

export { parameterize as default }
75 changes: 22 additions & 53 deletions src/util/write-payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,12 @@ export class WritePayload<T extends SpraypaintBase> {
const attrs: ModelRecord<T> = {}

this._eachAttribute((key, value, attrDef) => {
if (!this.model.isPersisted || (<any>this.model.changes())[key]) {
let writeKey = this.model.klass.serializeKey(key)
let writeKey = this.model.klass.serializeKey(key)

if (attrDef.type === Number && (value as any) === "") {
attrs[writeKey] = null
} else {
attrs[writeKey] = value
}
if (attrDef.type === Number && (value as any) === "") {
attrs[writeKey] = null
} else {
attrs[writeKey] = value
}
})

Expand Down Expand Up @@ -82,57 +80,41 @@ export class WritePayload<T extends SpraypaintBase> {

postProcess() {
this.removeDeletions(this.model, this.includeDirective)
this.model.resetRelationTracking(this.includeDirective)
this.model.resetRelationTracking()
}

relationships(): object {
const _relationships: any = {}

Object.keys(this.includeDirective).forEach((key: any) => {
const nested = (<any>this.includeDirective)[key]
Object.keys(this.model.klass.attributeList).forEach((key: string) => {
let attribute: Attribute = this.model.klass.attributeList[key]
let attributeName = attribute.name
if (!attribute.isRelationship) {
// Don't process attributes that are not relations
return
}

const nested = (<any>this.includeDirective)[key]
let idOnly = false
if (key.indexOf(".") > -1) {
key = key.split(".")[0]
idOnly = true
}

let data: any
const relatedModels = (<any>this.model)[key]
let data: any = null
const relatedModels = (<any>this.model)[attributeName]
if (relatedModels) {
if (Array.isArray(relatedModels)) {
data = []
relatedModels.forEach(relatedModel => {
if (
!this._isNewAndMarkedForDestruction(relatedModel) &&
(idOnly ||
this.model.hasDirtyRelation(key, relatedModel) ||
relatedModel.isDirty(nested))
) {
data.push(this._processRelatedModel(relatedModel, nested, idOnly))
}
data.push(this._processRelatedModel(relatedModel, nested, idOnly))
})
if (data.length === 0) {
data = null
}
} else {
// Either the related model is dirty, or it's a dirty relation
// (maybe the "department" is not dirty, but the employee changed departments
// or the model is new
if (
!this._isNewAndMarkedForDestruction(relatedModels) &&
(idOnly ||
this.model.hasDirtyRelation(key, relatedModels) ||
relatedModels.isDirty(nested))
) {
data = this._processRelatedModel(relatedModels, nested, idOnly)
}
}

if (data) {
_relationships[this.model.klass.serializeKey(key)] = { data }
data = this._processRelatedModel(relatedModels, nested, idOnly)
}
}

_relationships[this.model.klass.serializeKey(attributeName)] = { data }
})

return _relationships
Expand Down Expand Up @@ -230,26 +212,13 @@ export class WritePayload<T extends SpraypaintBase> {
identifier["temp-id"] = model.temp_id
}

let method: JsonapiResourceMethod
if (model.isPersisted) {
if (model.isMarkedForDestruction) {
method = "destroy"
} else if (model.isMarkedForDisassociation) {
method = "disassociate"
} else {
method = "update"
}
} else {
method = "create"
}
identifier.method = method

return identifier
}

private _pushInclude(include: any) {
if (!this._isIncluded(include)) {
this.included.push(include)
// We don't want the included part in the json-payload for writing
// this.included.push(include)
}
}

Expand Down
Loading