Skip to content
Merged
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
20 changes: 17 additions & 3 deletions client/instanceProxyHandler.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import client from './client'
import { generateContext } from './context'
import context, { generateContext } from './context'
import { generateObjectProxy } from './objectProxyHandler'

export const instanceProxies = new WeakMap()
Expand All @@ -15,8 +15,22 @@ const instanceProxyHandler = {
}
const { [name]: named } = {
[name]: (args) => {
const context = generateContext({ ...target._attributes, ...args })
return target[name].call(proxy, context)
const scopedContext = generateContext({ ...target._attributes, ...args })
let result
try {
result = target[name].call(proxy, scopedContext)
} catch (error) {
context.catch && context.catch(error)
return null
}
if (result instanceof Promise) {
return new Promise((resolve, reject) => {
result.then(resolve).catch((error) => {
context.catch ? context.catch(error) : reject(error)
})
})
}
return result
},
}
return named
Expand Down
3 changes: 3 additions & 0 deletions server/printError.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import context from './context'

export default function (error) {
context.catch && context.catch(error)
const lines = error.stack.split(`\n`)
let initiator = lines.find((line) => line.indexOf('Proxy') > -1)
if (initiator) {
Expand Down
20 changes: 19 additions & 1 deletion server/reqres.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,20 @@
const reqres = {}
class ReqRes {

request = null
response = null

set(request, response) {
this.request = request
this.response = response
}

clear() {
this.request = null
this.response = null
}

}

const reqres = new ReqRes()

export default reqres
21 changes: 15 additions & 6 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ for (const method of ['get', 'post', 'put', 'patch', 'delete', 'all']) {
server[method] = function (...args) {
if (typeof args[1] === 'function' && args[1].name === '_invoke') {
return original(args[0], bodyParser.text({ limit: server.maximumPayloadSize }), async (request, response) => {
reqres.set(request, response)
const params = {}
for (const key of Object.keys(request.params)) {
params[key] = extractParamValue(request.params[key])
Expand All @@ -53,9 +54,11 @@ for (const method of ['get', 'post', 'put', 'patch', 'delete', 'all']) {
try {
const subcontext = generateContext({ request, response, ...params })
const result = await args[1](subcontext)
reqres.clear()
response.json(result)
} catch (error) {
printError(error)
reqres.clear()
response.status(500).json({})
}
})
Expand Down Expand Up @@ -224,6 +227,7 @@ server.start = function () {

server.all(`/${prefix}/:hash/:methodName.json`, async (request, response) => {
const payload = request.method === 'GET' ? request.query.payload : request.body
reqres.set(request, response)
const args = deserialize(payload)
const { hash, methodName } = request.params
const [invokerHash, boundHash] = hash.split('-')
Expand All @@ -241,12 +245,15 @@ server.start = function () {
try {
const subcontext = generateContext({ request, response, ...args })
const result = await method.call(boundKlass, subcontext)
reqres.clear()
response.json({ result })
} catch (error) {
printError(error)
reqres.clear()
response.status(500).json({})
}
} else {
reqres.clear()
response.status(404).json({})
}
})
Expand All @@ -255,21 +262,23 @@ server.start = function () {
if (request.originalUrl.split('?')[0].indexOf('.') > -1) {
return next()
}
reqres.request = request
reqres.response = response
reqres.set(request, response)
const scope = await prerender(request, response)
if (!response.headersSent) {
const status = scope.context.page.status
const html = template(scope)
reqres.request = null
reqres.response = null
reqres.clear()
response.status(status).send(html)
} else {
reqres.request = null
reqres.response = null
reqres.clear()
}
})

server.use((error, _request, response, _next) => {
printError(error)
response.status(500).json({})
})

if (!server.less) {
if (!server.port) {
console.info('\x1b[31mServer port is not defined!\x1b[0m')
Expand Down
6 changes: 6 additions & 0 deletions tests/client.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Nullstack from 'nullstack'

import Application from './src/Application'
import CatchError from './src/CatchError.njs'
import vueable from './src/plugins/vueable'

Nullstack.use(vueable)
Expand All @@ -12,4 +13,9 @@ context.start = function () {
setTimeout(() => (context.startTimedValue = true), 1000)
}

context.catch = async function (error) {
CatchError.logError({ message: error.message })
console.error(error)
}

export default context
14 changes: 14 additions & 0 deletions tests/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import Nullstack from 'nullstack'
import cors from 'cors'

import Application from './src/Application'
import CatchError from './src/CatchError'
import ContextProject from './src/ContextProject'
import ContextSecrets from './src/ContextSecrets'
import ContextSettings from './src/ContextSettings'
import ContextWorker from './src/ContextWorker'
import ExposedServerFunctions from './src/ExposedServerFunctions'
import vueable from './src/plugins/vueable'
import ReqRes from './src/ReqRes'

Nullstack.use(vueable)

Expand Down Expand Up @@ -40,6 +42,9 @@ context.server.put('/data/put/:param', ExposedServerFunctions.getData)
context.server.patch('/data/patch/:param', ExposedServerFunctions.getData)
context.server.delete('/data/delete/:param', ExposedServerFunctions.getData)

context.server.get('/exposed-server-function-url.json', ReqRes.exposedServerFunction)
context.server.get('/nested-exposed-server-function-url.json', ReqRes.nestedExposedServerFunction)

context.server.get('/custom-api-before-start', (request, response) => {
response.json({ startValue: context.startValue })
})
Expand All @@ -57,6 +62,10 @@ for (const method of methods) {
})
}

context.server.get('/vaidamerdanaapi.json', (_request, response) => {
response.vaidamerdanaapi()
})

context.startIncrementalValue = 0

context.start = async function () {
Expand All @@ -68,4 +77,9 @@ context.start = async function () {
context.startIncrementalValue++
}

context.catch = async function (error) {
CatchError.logError({ message: error.message })
console.error(error)
}

export default context
4 changes: 4 additions & 0 deletions tests/src/Application.njs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import AnchorModifiers from './AnchorModifiers'
import './Application.css'
import ArrayAttributes from './ArrayAttributes'
import BodyFragment from './BodyFragment'
import CatchError from './CatchError'
import ChildComponent from './ChildComponent'
import ComponentTernary from './ComponentTernary'
import Context from './Context'
Expand Down Expand Up @@ -40,6 +41,7 @@ import PublicServerFunctions from './PublicServerFunctions.njs'
import PureComponents from './PureComponents'
import Refs from './Refs'
import RenderableComponent from './RenderableComponent'
import ReqRes from './ReqRes'
import RoutesAndParams from './RoutesAndParams'
import RouteScroll from './RouteScroll'
import ServerFunctions from './ServerFunctions'
Expand Down Expand Up @@ -137,6 +139,8 @@ class Application extends Nullstack {
<RouteScroll route="/route-scroll/*" key="routeScroll" />
<IsomorphicImport route="/isomorphic-import" />
<ExposedServerFunctions route="/exposed-server-functions" />
<CatchError route="/catch-error" />
<ReqRes route="/reqres" />
<ErrorPage route="*" />
</body>
)
Expand Down
50 changes: 50 additions & 0 deletions tests/src/CatchError.njs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import Nullstack from 'nullstack'

import { appendFileSync } from 'fs'

const error = new Error('Panic in the system, someone missconfigured me!')

class CatchError extends Nullstack {

static async logError({ message, environment }) {
const folder = environment.production ? '.production' : '.development'
appendFileSync(`${folder}/exceptions.txt`, `${message}\n`)
}

static async getServerFunction() {
throw error
}

async oneErrorPls() {
throw error
}

async hydrate({ params }) {
if (params.error === 'hydrate') {
this.vaidamerdanoclient()
}
}

update() {
this.hydrated = true
}

async initiate({ params, page }) {
if (params.error === 'initiate' && page.status === 200) {
this.vaidamerdanoserver()
} else if (params.error === 'initiateServerFunction') {
await this.getServerFunction()
}
}

render() {
return (
<div data-hydrated={this.hydrated}>
<button onclick={this.oneErrorPls}> Error </button>
</div>
)
}

}

export default CatchError
34 changes: 34 additions & 0 deletions tests/src/CatchError.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const { readFileSync } = require('fs')

describe('CatchError initiate', () => {
test('errors caused by instances can be caught on the server', async () => {
await page.goto('http://localhost:6969/catch-error?error=initiate')
const logs = readFileSync('.production/exceptions.txt', 'utf-8')
expect(logs.includes('this.vaidamerdanoserver is not a function')).toBeTruthy()
})
})

describe('CatchError initiateServerFunction', () => {
test('errors caused by server functions can be caught on the server', async () => {
await page.goto('http://localhost:6969/catch-error?error=initiateServerFunction')
const logs = readFileSync('.production/exceptions.txt', 'utf-8')
expect(logs.includes('Panic in the system, someone missconfigured me!')).toBeTruthy()
})
})

describe('CatchError hydrate', () => {
test('errors caused by instances can be caught on the client', async () => {
await page.goto('http://localhost:6969/catch-error?error=hydrate')
await page.waitForSelector('[data-hydrated]')
const logs = readFileSync('.production/exceptions.txt', 'utf-8')
expect(logs.includes('this.vaidamerdanoclient is not a function')).toBeTruthy()
})
})

describe('CatchError api', () => {
test('errors caused by api routes can be caught on the server', async () => {
await page.goto('http://localhost:6969/vaidamerdanaapi.json')
const logs = readFileSync('.production/exceptions.txt', 'utf-8')
expect(logs.includes('response.vaidamerdanaapi is not a function')).toBeTruthy()
})
})
82 changes: 82 additions & 0 deletions tests/src/ReqRes.njs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import Nullstack from 'nullstack'

class ReqRes extends Nullstack {

static async innerNestedServerFunctionFromClient(context) {
return context.request.originalUrl
}

static async nestedServerFunctionFromClient() {
return this.innerNestedServerFunctionFromClient()
}

static async serverFunctionFromClient(context) {
return context.request.originalUrl
}

static async innerNestedServerFunction(context) {
return context.request.originalUrl
}

static async serverFunction(context) {
return context.request.originalUrl
}

static async nestedServerFunction() {
return this.innerNestedServerFunction()
}

static async innerNestedExposedServerFunction(context) {
return context.request.originalUrl
}

static async nestedExposedServerFunction() {
return this.innerNestedExposedServerFunction()
}

static async exposedServerFunction(context) {
return context.request.originalUrl
}

async initiate() {
this.serverFunctionUrl = await ReqRes.serverFunction()
this.nestedServerFunctionUrl = await ReqRes.nestedServerFunction()
}

async fetchServerFunction({ slug }) {
const response = await fetch(`/${slug}.json`)
return response.json()
}

async hydrate() {
this.serverFunctionFromClientUrl = await ReqRes.serverFunctionFromClient()
this.nestedServerFunctionFromClientUrl = await ReqRes.nestedServerFunctionFromClient()
this.exposedServerFunctionUrl = await this.fetchServerFunction({ slug: 'exposed-server-function-url' })
this.nestedExposedServerFunctionUrl = await this.fetchServerFunction({ slug: 'nested-exposed-server-function-url' })
}

render() {
return (
<div
data-server-function={this.serverFunctionUrl === '/reqres'}
data-nested-server-function={this.nestedServerFunctionUrl === '/reqres'}
data-server-function-from-client={
this.serverFunctionFromClientUrl ===
'/nullstack/3f8aea65a953b05e7a7a412d1188ac14/serverFunctionFromClient.json'
}
data-nested-server-function-from-client={
this.nestedServerFunctionFromClientUrl ===
'/nullstack/3f8aea65a953b05e7a7a412d1188ac14/nestedServerFunctionFromClient.json'
}
data-exposed-server-function={this.exposedServerFunctionUrl === '/exposed-server-function-url.json'}
data-exposed-nested-server-function={
this.nestedExposedServerFunctionUrl === '/nested-exposed-server-function-url.json'
}
data-hydrated={this.hydrated}
/>
)
}

}

export default ReqRes
Loading